ziphy 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.
ziphy/__init__.py ADDED
@@ -0,0 +1,28 @@
1
+ """ziphy: Animate meteorological Zarr, Icechunk, and virtual Zarr datastores."""
2
+
3
+ from ziphy.coords import CoordinateResolutionError, SelectionSpec
4
+ from ziphy.params import ParameterResolutionError, ResolvedParam, resolve_param, resolve_params
5
+ from ziphy.prep import DatasetInspection, inspect_dataset
6
+ from ziphy.render import RenderConfig, RenderResult, create_gif
7
+ from ziphy.store import DatastoreOpenError, OpenedDatastore, StoreOptions, open_datastore
8
+
9
+ __version__ = "0.1.0"
10
+
11
+ __all__ = [
12
+ "CoordinateResolutionError",
13
+ "DatasetInspection",
14
+ "DatastoreOpenError",
15
+ "OpenedDatastore",
16
+ "ParameterResolutionError",
17
+ "RenderConfig",
18
+ "RenderResult",
19
+ "ResolvedParam",
20
+ "SelectionSpec",
21
+ "StoreOptions",
22
+ "__version__",
23
+ "create_gif",
24
+ "inspect_dataset",
25
+ "open_datastore",
26
+ "resolve_param",
27
+ "resolve_params",
28
+ ]
ziphy/cli.py ADDED
@@ -0,0 +1,378 @@
1
+ """Typer CLI for inspecting and animating meteorological Zarr/Icechunk datastores."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Annotated
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+ from rich.progress import BarColumn, Progress, SpinnerColumn, TextColumn, TimeRemainingColumn
12
+ from rich.table import Table
13
+
14
+ from ziphy.coords import (
15
+ CoordinateResolutionError,
16
+ ReduceOp,
17
+ parse_isel_items,
18
+ parse_sel_items,
19
+ )
20
+ from ziphy.params import ParameterResolutionError
21
+ from ziphy.prep import inspect_dataset
22
+ from ziphy.projection import ProjectionChoice
23
+ from ziphy.render import RenderConfig, create_gif
24
+ from ziphy.store import DatastoreOpenError, StoreFormat, StoreOptions, open_datastore
25
+
26
+ app = typer.Typer(
27
+ name="ziphy",
28
+ help="Animate meteorological Zarr, Icechunk, and virtual Zarr datastores into GIFs.",
29
+ no_args_is_help=True,
30
+ )
31
+ console = Console()
32
+ err_console = Console(stderr=True)
33
+
34
+
35
+ def _parse_bbox(raw: str | None) -> tuple[float, float, float, float] | None:
36
+ if raw is None:
37
+ return None
38
+ parts = [p.strip() for p in raw.split(",")]
39
+ if len(parts) != 4:
40
+ raise typer.BadParameter(
41
+ "--bbox must have 4 comma-separated numbers: lon_min,lat_min,lon_max,lat_max"
42
+ )
43
+ try:
44
+ vals = tuple(float(p) for p in parts)
45
+ return (vals[0], vals[1], vals[2], vals[3])
46
+ except ValueError as exc:
47
+ raise typer.BadParameter("--bbox values must be numeric.") from exc
48
+
49
+
50
+ def _parse_pair(raw: str | None, name: str, cast: type[int] | type[float]) -> tuple | None:
51
+ if raw is None:
52
+ return None
53
+ sep = "x" if "x" in raw.lower() and "," not in raw else ","
54
+ parts = [p.strip() for p in raw.lower().split(sep)]
55
+ if len(parts) != 2:
56
+ raise typer.BadParameter(f"{name} must be formatted as A,B or AxB.")
57
+ try:
58
+ return (cast(parts[0]), cast(parts[1]))
59
+ except ValueError as exc:
60
+ raise typer.BadParameter(f"Invalid numeric values in {name}: {raw}") from exc
61
+
62
+
63
+ def _parse_csv_list(raw: str | None) -> list[str] | None:
64
+ if raw is None:
65
+ return None
66
+ return [item.strip() for item in raw.split(",") if item.strip()]
67
+
68
+
69
+ @app.command("inspect")
70
+ def inspect_cmd(
71
+ source: Annotated[
72
+ str, typer.Argument(help="Path or URL to Zarr, Icechunk, or Kerchunk store.")
73
+ ],
74
+ store_format: Annotated[
75
+ StoreFormat,
76
+ typer.Option("--format", "-f", help="Datastore format (auto, zarr, icechunk, kerchunk)."),
77
+ ] = "auto",
78
+ group: Annotated[str | None, typer.Option("--group", "-g", help="Zarr group path.")] = None,
79
+ branch: Annotated[str, typer.Option("--branch", help="Icechunk branch name.")] = "main",
80
+ tag: Annotated[str | None, typer.Option("--tag", help="Icechunk tag name.")] = None,
81
+ snapshot_id: Annotated[
82
+ str | None, typer.Option("--snapshot-id", help="Icechunk snapshot ID.")
83
+ ] = None,
84
+ anon: Annotated[bool, typer.Option("--anon", help="Use anonymous cloud access.")] = False,
85
+ region: Annotated[
86
+ str | None, typer.Option("--region", help="Cloud region (e.g. us-east-1).")
87
+ ] = None,
88
+ remote_protocol: Annotated[
89
+ str | None, typer.Option("--remote-protocol", help="Remote protocol for Kerchunk refs.")
90
+ ] = None,
91
+ ) -> None:
92
+ """Inspect datastore variables, WMO IDs, CF names, temporal bounds, and realizations."""
93
+ opts = StoreOptions(
94
+ format=store_format,
95
+ group=group,
96
+ branch=branch,
97
+ tag=tag,
98
+ snapshot_id=snapshot_id,
99
+ anon=anon,
100
+ region=region,
101
+ remote_protocol=remote_protocol,
102
+ )
103
+ try:
104
+ opened = open_datastore(source, opts)
105
+ except DatastoreOpenError as exc:
106
+ err_console.print(f"[red]Error:[/red] {exc}")
107
+ raise typer.Exit(code=1) from exc
108
+
109
+ info = inspect_dataset(opened.dataset, opened.source_label, opened.backend)
110
+
111
+ real_line = (
112
+ f"[bold]Realization dim:[/bold] {info.realization_dim} ({info.realization_count} members)"
113
+ if info.realization_dim
114
+ else "[bold]Realization dim:[/bold] none"
115
+ )
116
+ header_lines = [
117
+ f"[bold]Source:[/bold] {info.source}",
118
+ f"[bold]Backend:[/bold] {info.backend}",
119
+ "[bold]Dims:[/bold] " + ", ".join(f"{k}={v}" for k, v in info.dims.items()),
120
+ real_line,
121
+ ]
122
+ console.print(Panel("\n".join(header_lines), title="ziphy inspect", expand=False))
123
+
124
+ if info.time_dims:
125
+ t_table = Table(title="Temporal Dimensions")
126
+ t_table.add_column("Dimension", style="cyan")
127
+ t_table.add_column("Length", justify="right")
128
+ t_table.add_column("Start")
129
+ t_table.add_column("End")
130
+ for td in info.time_dims:
131
+ t_table.add_row(td.name, str(td.size), td.start_label, td.end_label)
132
+ console.print(t_table)
133
+
134
+ v_table = Table(title="Variables")
135
+ v_table.add_column("Variable", style="green")
136
+ v_table.add_column("CF standard_name")
137
+ v_table.add_column("WMO ID", style="yellow")
138
+ v_table.add_column("Units")
139
+ v_table.add_column("Dimensions")
140
+ v_table.add_column("Grid Mapping")
141
+ for vs in info.variables:
142
+ dims_fmt = ", ".join(f"{d}({s})" for d, s in zip(vs.dims, vs.shape, strict=True))
143
+ v_table.add_row(
144
+ vs.name,
145
+ vs.standard_name or "-",
146
+ vs.wmo_id or "-",
147
+ vs.units or "-",
148
+ dims_fmt,
149
+ vs.grid_mapping or "-",
150
+ )
151
+ console.print(v_table)
152
+
153
+
154
+ @app.command("render")
155
+ def render_cmd(
156
+ source: Annotated[
157
+ str, typer.Argument(help="Path or URL to Zarr, Icechunk, or Kerchunk store.")
158
+ ],
159
+ param: Annotated[
160
+ list[str],
161
+ typer.Option(
162
+ "--param",
163
+ "-p",
164
+ help=(
165
+ "Parameter by variable name, CF standard_name, WMO paramId (e.g. 167), "
166
+ "or GRIB2 triplet (0-0-0). Repeat for multiplot."
167
+ ),
168
+ ),
169
+ ],
170
+ output: Annotated[Path, typer.Option("--output", "-o", help="Output GIF path.")] = Path(
171
+ "output.gif"
172
+ ),
173
+ time_dim: Annotated[
174
+ str | None, typer.Option("--time-dim", "-t", help="Temporal dimension to animate over.")
175
+ ] = None,
176
+ start_date: Annotated[
177
+ str | None,
178
+ typer.Option(
179
+ "--start-date",
180
+ "--start",
181
+ help="Start date/timestamp (ISO) or duration (e.g. 0h).",
182
+ ),
183
+ ] = None,
184
+ end_date: Annotated[
185
+ str | None,
186
+ typer.Option(
187
+ "--end-date",
188
+ "--end",
189
+ help="End date/timestamp (ISO) or duration (e.g. 48h).",
190
+ ),
191
+ ] = None,
192
+ step: Annotated[int, typer.Option("--step", help="Frame stride along temporal dimension.")] = 1,
193
+ max_frames: Annotated[
194
+ int | None, typer.Option("--max-frames", help="Maximum number of frames to render.")
195
+ ] = None,
196
+ realization_dim: Annotated[
197
+ str | None,
198
+ typer.Option("--realization-dim", help="Explicit realization/ensemble dimension name."),
199
+ ] = None,
200
+ realization: Annotated[
201
+ str | None, typer.Option("--realization", "-r", help="Select a single realization member.")
202
+ ] = None,
203
+ realizations: Annotated[
204
+ str | None,
205
+ typer.Option("--realizations", help="Comma-separated realization subset for single-param."),
206
+ ] = None,
207
+ max_realizations: Annotated[
208
+ int | None,
209
+ typer.Option("--max-realizations", help="Cap realizations shown in ensemble grid."),
210
+ ] = None,
211
+ reduce: Annotated[
212
+ ReduceOp | None,
213
+ typer.Option("--reduce", help="Reduce realization dim (mean, std, min, max, median)."),
214
+ ] = None,
215
+ sel: Annotated[
216
+ list[str] | None,
217
+ typer.Option("--sel", help="Pin extra dimension by label (dim=value). Repeatable."),
218
+ ] = None,
219
+ isel: Annotated[
220
+ list[str] | None,
221
+ typer.Option("--isel", help="Pin extra dimension by index (dim=index). Repeatable."),
222
+ ] = None,
223
+ bbox: Annotated[
224
+ str | None, typer.Option("--bbox", help="Spatial crop: lon_min,lat_min,lon_max,lat_max.")
225
+ ] = None,
226
+ proj: Annotated[
227
+ ProjectionChoice,
228
+ typer.Option(
229
+ "--proj",
230
+ help="Map projection (auto, platecarree, robinson, orthographic, geostationary, none).",
231
+ ),
232
+ ] = "auto",
233
+ cmap: Annotated[
234
+ str | None, typer.Option("--cmap", help="Matplotlib colormap override.")
235
+ ] = None,
236
+ cmaps: Annotated[
237
+ str | None, typer.Option("--cmaps", help="Comma-separated colormaps for multiplot panels.")
238
+ ] = None,
239
+ vmin: Annotated[float | None, typer.Option("--vmin", help="Color scale minimum.")] = None,
240
+ vmax: Annotated[float | None, typer.Option("--vmax", help="Color scale maximum.")] = None,
241
+ robust: Annotated[
242
+ bool, typer.Option("--robust", help="Use 2nd-98th percentile color bounds.")
243
+ ] = False,
244
+ coarsen: Annotated[
245
+ int | None, typer.Option("--coarsen", help="Explicit spatial stride factor.")
246
+ ] = None,
247
+ max_pixels: Annotated[
248
+ int,
249
+ typer.Option("--max-pixels", help="Auto-downsample axes larger than this pixel count."),
250
+ ] = 900,
251
+ layout: Annotated[
252
+ str | None, typer.Option("--layout", help="Subplot grid layout (e.g. 2x2 or 3,6).")
253
+ ] = None,
254
+ dpi: Annotated[int, typer.Option("--dpi", help="Figure DPI.")] = 100,
255
+ figsize: Annotated[
256
+ str | None, typer.Option("--figsize", help="Figure size in inches (e.g. 12,8).")
257
+ ] = None,
258
+ fps: Annotated[float, typer.Option("--fps", help="Animation frames per second.")] = 4.0,
259
+ duration_ms: Annotated[
260
+ int | None, typer.Option("--duration-ms", help="Explicit frame duration in milliseconds.")
261
+ ] = None,
262
+ loop: Annotated[int, typer.Option("--loop", help="GIF loop count (0 = infinite).")] = 0,
263
+ coastlines: Annotated[
264
+ bool, typer.Option("--coastlines/--no-coastlines", help="Draw coastlines.")
265
+ ] = True,
266
+ borders: Annotated[bool, typer.Option("--borders", help="Draw country borders.")] = False,
267
+ gridlines: Annotated[bool, typer.Option("--gridlines", help="Draw lat/lon gridlines.")] = False,
268
+ title: Annotated[
269
+ str | None, typer.Option("--title", help="Custom figure title prefix.")
270
+ ] = None,
271
+ store_format: Annotated[
272
+ StoreFormat,
273
+ typer.Option("--format", "-f", help="Datastore format (auto, zarr, icechunk, kerchunk)."),
274
+ ] = "auto",
275
+ group: Annotated[str | None, typer.Option("--group", "-g", help="Zarr group path.")] = None,
276
+ branch: Annotated[str, typer.Option("--branch", help="Icechunk branch name.")] = "main",
277
+ tag: Annotated[str | None, typer.Option("--tag", help="Icechunk tag name.")] = None,
278
+ snapshot_id: Annotated[
279
+ str | None, typer.Option("--snapshot-id", help="Icechunk snapshot ID.")
280
+ ] = None,
281
+ anon: Annotated[bool, typer.Option("--anon", help="Use anonymous cloud access.")] = False,
282
+ region: Annotated[
283
+ str | None, typer.Option("--region", help="Cloud region (e.g. us-east-1).")
284
+ ] = None,
285
+ remote_protocol: Annotated[
286
+ str | None, typer.Option("--remote-protocol", help="Remote protocol for Kerchunk refs.")
287
+ ] = None,
288
+ ) -> None:
289
+ """Render an animated GIF iterating over a temporal dimension (and optional date range)."""
290
+ try:
291
+ sel_dict = parse_sel_items(sel)
292
+ isel_dict = parse_isel_items(isel)
293
+ bbox_tuple = _parse_bbox(bbox)
294
+ layout_tuple = _parse_pair(layout, "--layout", int)
295
+ figsize_tuple = _parse_pair(figsize, "--figsize", float)
296
+ real_subset = _parse_csv_list(realizations)
297
+ cmaps_list = _parse_csv_list(cmaps)
298
+
299
+ store_opts = StoreOptions(
300
+ format=store_format,
301
+ group=group,
302
+ branch=branch,
303
+ tag=tag,
304
+ snapshot_id=snapshot_id,
305
+ anon=anon,
306
+ region=region,
307
+ remote_protocol=remote_protocol,
308
+ )
309
+ cfg = RenderConfig(
310
+ params=param,
311
+ output=output,
312
+ time_dim=time_dim,
313
+ start_date=start_date,
314
+ end_date=end_date,
315
+ step=step,
316
+ max_frames=max_frames,
317
+ realization_dim=realization_dim,
318
+ realization=realization,
319
+ realizations=real_subset,
320
+ max_realizations=max_realizations,
321
+ reduce=reduce,
322
+ sel=sel_dict or None,
323
+ isel=isel_dict or None,
324
+ bbox=bbox_tuple,
325
+ projection=proj,
326
+ cmap=cmap,
327
+ cmaps=cmaps_list,
328
+ vmin=vmin,
329
+ vmax=vmax,
330
+ robust=robust,
331
+ coarsen=coarsen,
332
+ max_pixels=max_pixels,
333
+ layout=layout_tuple,
334
+ dpi=dpi,
335
+ figsize=figsize_tuple,
336
+ fps=fps,
337
+ duration_ms=duration_ms,
338
+ loop=loop,
339
+ coastlines=coastlines,
340
+ borders=borders,
341
+ gridlines=gridlines,
342
+ title=title,
343
+ )
344
+
345
+ with Progress(
346
+ SpinnerColumn(),
347
+ TextColumn("[progress.description]{task.description}"),
348
+ BarColumn(),
349
+ TextColumn("{task.completed}/{task.total} frames"),
350
+ TimeRemainingColumn(),
351
+ console=console,
352
+ transient=True,
353
+ ) as progress:
354
+ task_id = progress.add_task("Rendering GIF frames...", total=None)
355
+
356
+ def _on_frame(done: int, total: int) -> None:
357
+ progress.update(task_id, total=total, completed=done)
358
+
359
+ result = create_gif(source, cfg, store_options=store_opts, on_frame=_on_frame)
360
+
361
+ size_kb = result.file_size_bytes / 1024.0
362
+ console.print(
363
+ f"[green]Created[/green] {result.output_path} "
364
+ f"({result.n_frames} frames, {result.n_panels} panel(s), "
365
+ f"mode={result.mode}, {size_kb:.1f} KiB)"
366
+ )
367
+ except (
368
+ DatastoreOpenError,
369
+ ParameterResolutionError,
370
+ CoordinateResolutionError,
371
+ ValueError,
372
+ ) as exc:
373
+ err_console.print(f"[red]Error:[/red] {exc}")
374
+ raise typer.Exit(code=1) from exc
375
+
376
+
377
+ if __name__ == "__main__":
378
+ app()