planetary-datasets 0.0.10__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.
Files changed (157) hide show
  1. planetary_datasets/__init__.py +40 -0
  2. planetary_datasets/base.py +329 -0
  3. planetary_datasets/common/__init__.py +40 -0
  4. planetary_datasets/common/dataset.py +143 -0
  5. planetary_datasets/common/download.py +531 -0
  6. planetary_datasets/common/earthdata.py +138 -0
  7. planetary_datasets/common/generations.py +625 -0
  8. planetary_datasets/common/grib.py +341 -0
  9. planetary_datasets/common/hdf5_chunk_index.py +641 -0
  10. planetary_datasets/common/hub.py +80 -0
  11. planetary_datasets/common/lazy_fields.py +502 -0
  12. planetary_datasets/common/lossless.py +111 -0
  13. planetary_datasets/common/maap.py +133 -0
  14. planetary_datasets/common/multidim.py +718 -0
  15. planetary_datasets/common/naming.py +1023 -0
  16. planetary_datasets/common/parquet.py +142 -0
  17. planetary_datasets/common/paths.py +95 -0
  18. planetary_datasets/common/staged.py +42 -0
  19. planetary_datasets/common/store.py +779 -0
  20. planetary_datasets/common/time.py +34 -0
  21. planetary_datasets/config.py +327 -0
  22. planetary_datasets/memory.py +321 -0
  23. planetary_datasets/providers/__init__.py +11 -0
  24. planetary_datasets/providers/_timestamps.py +38 -0
  25. planetary_datasets/providers/amps.py +978 -0
  26. planetary_datasets/providers/arome.py +516 -0
  27. planetary_datasets/providers/cams.py +873 -0
  28. planetary_datasets/providers/cfs.py +250 -0
  29. planetary_datasets/providers/cmems/__init__.py +58 -0
  30. planetary_datasets/providers/cmems/client.py +269 -0
  31. planetary_datasets/providers/cmems/global_ocean.py +333 -0
  32. planetary_datasets/providers/cmems/wave.py +226 -0
  33. planetary_datasets/providers/corra.py +376 -0
  34. planetary_datasets/providers/destine.py +236 -0
  35. planetary_datasets/providers/dmi_harmonie.py +375 -0
  36. planetary_datasets/providers/earth2studio_download.py +1268 -0
  37. planetary_datasets/providers/earth2studio_obs.py +291 -0
  38. planetary_datasets/providers/eeps.py +186 -0
  39. planetary_datasets/providers/eumetsat/__init__.py +1 -0
  40. planetary_datasets/providers/eumetsat/mtg.py +174 -0
  41. planetary_datasets/providers/eumetsat/mtg_irs.py +445 -0
  42. planetary_datasets/providers/eumetsat/sentinel4.py +543 -0
  43. planetary_datasets/providers/geos.py +245 -0
  44. planetary_datasets/providers/gfs.py +492 -0
  45. planetary_datasets/providers/glofas.py +488 -0
  46. planetary_datasets/providers/gmgsi.py +390 -0
  47. planetary_datasets/providers/goes_l2_points.py +716 -0
  48. planetary_datasets/providers/hawaii_nam.py +102 -0
  49. planetary_datasets/providers/himawari_h9_tiles.py +101 -0
  50. planetary_datasets/providers/hrrr_alaska.py +69 -0
  51. planetary_datasets/providers/hurdat2.py +632 -0
  52. planetary_datasets/providers/icon.py +1565 -0
  53. planetary_datasets/providers/icon_d2_ruc_mirror.py +278 -0
  54. planetary_datasets/providers/icon_v1.py +1712 -0
  55. planetary_datasets/providers/icon_v1_catalog.py +2271 -0
  56. planetary_datasets/providers/icon_v1_mirror.py +170 -0
  57. planetary_datasets/providers/ifs.py +518 -0
  58. planetary_datasets/providers/imerg.py +527 -0
  59. planetary_datasets/providers/kenda.py +406 -0
  60. planetary_datasets/providers/kenda_download.py +403 -0
  61. planetary_datasets/providers/mars.py +452 -0
  62. planetary_datasets/providers/mars_icechunk.py +2940 -0
  63. planetary_datasets/providers/mars_pipeline.py +1463 -0
  64. planetary_datasets/providers/meps.py +543 -0
  65. planetary_datasets/providers/metoffice.py +1116 -0
  66. planetary_datasets/providers/mrms.py +552 -0
  67. planetary_datasets/providers/observations/__init__.py +46 -0
  68. planetary_datasets/providers/observations/_points.py +289 -0
  69. planetary_datasets/providers/observations/aeronet.py +244 -0
  70. planetary_datasets/providers/observations/aeronet_archive.py +1129 -0
  71. planetary_datasets/providers/observations/amdar.py +773 -0
  72. planetary_datasets/providers/observations/asos.py +205 -0
  73. planetary_datasets/providers/observations/base.py +524 -0
  74. planetary_datasets/providers/observations/cds.py +301 -0
  75. planetary_datasets/providers/observations/eurocontrol.py +161 -0
  76. planetary_datasets/providers/observations/ghcn.py +350 -0
  77. planetary_datasets/providers/observations/gnss.py +59 -0
  78. planetary_datasets/providers/observations/igra.py +699 -0
  79. planetary_datasets/providers/observations/isd.py +256 -0
  80. planetary_datasets/providers/observations/meteostat.py +202 -0
  81. planetary_datasets/providers/observations/midc.py +141 -0
  82. planetary_datasets/providers/observations/ncep_prepbufr.py +764 -0
  83. planetary_datasets/providers/observations/opensky.py +451 -0
  84. planetary_datasets/providers/observations/osmc.py +382 -0
  85. planetary_datasets/providers/observations/osmc_ragged.py +425 -0
  86. planetary_datasets/providers/observations/pvlive.py +217 -0
  87. planetary_datasets/providers/observations/rahm.py +90 -0
  88. planetary_datasets/providers/observations/solrad.py +121 -0
  89. planetary_datasets/providers/observations/sondehub.py +830 -0
  90. planetary_datasets/providers/observations/surfrad.py +140 -0
  91. planetary_datasets/providers/observations/uk_marine.py +577 -0
  92. planetary_datasets/providers/observations/upper_air_common.py +168 -0
  93. planetary_datasets/providers/observations/wis2_aircraft.py +569 -0
  94. planetary_datasets/providers/observations/wis2_archive.py +927 -0
  95. planetary_datasets/providers/observations/wis2_land.py +1061 -0
  96. planetary_datasets/providers/observations/wis2_land_hydrometric.py +412 -0
  97. planetary_datasets/providers/observations/wis2_land_radar.py +963 -0
  98. planetary_datasets/providers/observations/wis2_ocean.py +811 -0
  99. planetary_datasets/providers/observations/wis2_qc.py +1229 -0
  100. planetary_datasets/providers/observations/wis2_satellite.py +1469 -0
  101. planetary_datasets/providers/observations/wis2_satellite_products.py +536 -0
  102. planetary_datasets/providers/observations/wis2_tac.py +736 -0
  103. planetary_datasets/providers/observations/wis2_targets.py +489 -0
  104. planetary_datasets/providers/observations/wis2_upper_air.py +729 -0
  105. planetary_datasets/providers/observations/wis2_wind_profiler.py +840 -0
  106. planetary_datasets/providers/opera.py +191 -0
  107. planetary_datasets/providers/opera_download.py +325 -0
  108. planetary_datasets/providers/polar/__init__.py +83 -0
  109. planetary_datasets/providers/polar/_eumdac.py +227 -0
  110. planetary_datasets/providers/polar/_granule.py +342 -0
  111. planetary_datasets/providers/polar/_jpss.py +615 -0
  112. planetary_datasets/providers/polar/aeolus.py +610 -0
  113. planetary_datasets/providers/polar/earthcare.py +658 -0
  114. planetary_datasets/providers/polar/epct_download.py +87 -0
  115. planetary_datasets/providers/polar/jpss_atms.py +233 -0
  116. planetary_datasets/providers/polar/jpss_atms_l2.py +384 -0
  117. planetary_datasets/providers/polar/jpss_viirs.py +552 -0
  118. planetary_datasets/providers/polar/metop_amsua.py +80 -0
  119. planetary_datasets/providers/polar/metop_ascat.py +78 -0
  120. planetary_datasets/providers/polar/metop_avhrr.py +155 -0
  121. planetary_datasets/providers/polar/metop_gome.py +71 -0
  122. planetary_datasets/providers/polar/metop_iasi.py +113 -0
  123. planetary_datasets/providers/polar/metop_mhs.py +18 -0
  124. planetary_datasets/providers/polar/metop_sg.py +181 -0
  125. planetary_datasets/providers/polar/pace.py +416 -0
  126. planetary_datasets/providers/polar/pace_virtual.py +577 -0
  127. planetary_datasets/providers/radar.py +710 -0
  128. planetary_datasets/providers/regional_lam_common.py +441 -0
  129. planetary_datasets/providers/seasonal.py +335 -0
  130. planetary_datasets/providers/silam.py +341 -0
  131. planetary_datasets/providers/tempo.py +518 -0
  132. planetary_datasets/providers/virtualized/__init__.py +13 -0
  133. planetary_datasets/providers/virtualized/gem15.py +899 -0
  134. planetary_datasets/providers/virtualized/geos_cf.py +1122 -0
  135. planetary_datasets/providers/virtualized/geos_cf_names.py +346 -0
  136. planetary_datasets/providers/virtualized/gk2a_ami_fd.py +1190 -0
  137. planetary_datasets/providers/virtualized/goes_16_radf.py +22 -0
  138. planetary_datasets/providers/virtualized/goes_17.py +1189 -0
  139. planetary_datasets/providers/virtualized/goes_17_radf.py +22 -0
  140. planetary_datasets/providers/virtualized/goes_18_radf.py +21 -0
  141. planetary_datasets/providers/virtualized/goes_19_radf.py +22 -0
  142. planetary_datasets/providers/virtualized/goes_l2.py +863 -0
  143. planetary_datasets/providers/virtualized/goes_radf_common.py +3574 -0
  144. planetary_datasets/providers/virtualized/hafs.py +560 -0
  145. planetary_datasets/providers/virtualized/himawari_isatss.py +923 -0
  146. planetary_datasets/providers/virtualized/ingest_gk2a_fd.py +383 -0
  147. planetary_datasets/providers/virtualized/ingest_goes_radf.py +909 -0
  148. planetary_datasets/providers/virtualized/ingest_himawari_isatss.py +254 -0
  149. planetary_datasets/providers/virtualized/noaa_nests.py +684 -0
  150. planetary_datasets/providers/virtualized/nsrdb.py +2287 -0
  151. planetary_datasets/providers/virtualized/virtual_repo.py +391 -0
  152. planetary_datasets/utils.py +35 -0
  153. planetary_datasets-0.0.10.dist-info/METADATA +106 -0
  154. planetary_datasets-0.0.10.dist-info/RECORD +157 -0
  155. planetary_datasets-0.0.10.dist-info/WHEEL +5 -0
  156. planetary_datasets-0.0.10.dist-info/licenses/LICENSE +21 -0
  157. planetary_datasets-0.0.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,40 @@
1
+ """Planetary datasets: downloaders and processors for open environmental data.
2
+
3
+ Each dataset is a :class:`~planetary_datasets.base.BaseProvider` subclass under
4
+ ``planetary_datasets.providers``. Providers are driven either by the Dagster assets in
5
+ ``dags/`` or directly::
6
+
7
+ from planetary_datasets.providers.hawaii_nam import HawaiiNAMProvider
8
+
9
+ HawaiiNAMProvider().run_partition(pd.Timestamp("2026-01-01T00:00"))
10
+
11
+ Configuration comes from the environment and an optional ``.env`` file; see
12
+ :mod:`planetary_datasets.config` and ``.env.example``.
13
+ """
14
+
15
+ from planetary_datasets.base import BaseProvider
16
+ from planetary_datasets.config import Config, MissingCredential, get_config, load_config
17
+ from planetary_datasets.memory import (
18
+ MemoryLimitExceeded,
19
+ available_memory_gb,
20
+ estimate_dataset_gb,
21
+ memory_guard,
22
+ require_memory,
23
+ total_memory_gb,
24
+ )
25
+
26
+ __all__ = [
27
+ "BaseProvider",
28
+ "Config",
29
+ "MemoryLimitExceeded",
30
+ "MissingCredential",
31
+ "available_memory_gb",
32
+ "estimate_dataset_gb",
33
+ "get_config",
34
+ "load_config",
35
+ "memory_guard",
36
+ "require_memory",
37
+ "total_memory_gb",
38
+ ]
39
+
40
+ __version__ = "0.0.1"
@@ -0,0 +1,329 @@
1
+ """Base provider interface.
2
+
3
+ A provider knows how to fetch the inputs for one partition of a dataset and turn them into
4
+ an :class:`xarray.Dataset`. Everything else — opening the store, skipping work that is
5
+ already done, choosing compression, appending safely, watching memory — is handled here so
6
+ each provider stays small.
7
+
8
+ Subclasses set :attr:`name`, :attr:`append_dim` and :attr:`store_prefix`, and implement
9
+ :meth:`fetch` and :meth:`process`. Dagster assets call :meth:`run_partition`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import pathlib
16
+ import tempfile
17
+ from abc import ABC, abstractmethod
18
+ from typing import Iterator, List
19
+
20
+ import icechunk
21
+ import numpy as np
22
+ import pandas as pd
23
+ import xarray as xr
24
+ from loguru import logger
25
+
26
+ from planetary_datasets.common import naming
27
+ from planetary_datasets.common.store import ALIGNMENT_COORDS, axis_is_sorted
28
+ from planetary_datasets.common.store import (
29
+ bitround_dataset as _bitround_dataset,
30
+ )
31
+ from planetary_datasets.common.store import (
32
+ missing_timesteps as _missing_timesteps,
33
+ )
34
+ from planetary_datasets.common.store import (
35
+ sort_append_axis as _sort_append_axis,
36
+ )
37
+ from planetary_datasets.common.store import (
38
+ write_to_icechunk as _write_to_icechunk,
39
+ )
40
+ from planetary_datasets.config import Config, get_config
41
+ from planetary_datasets.memory import memory_guard, require_dataset_fits
42
+ from planetary_datasets.providers._timestamps import to_naive_utc
43
+
44
+
45
+ class BaseProvider(ABC):
46
+ """Abstract base provider used by the Dagster assets and the CLI.
47
+
48
+ Attributes:
49
+ name: Short identifier, used in logs and as the Dagster asset name.
50
+ append_dim: Dimension new data is appended along, usually ``time`` or ``init_time``.
51
+ store_prefix: Location of the store relative to the configured bucket, e.g.
52
+ ``bkr/dmi/hawaii_nams.icechunk``. Resolved to S3 or a local directory by
53
+ :class:`~planetary_datasets.config.Config`.
54
+ """
55
+
56
+ name: str
57
+ append_dim: str = "time"
58
+ store_prefix: str
59
+
60
+ #: Zarr group inside the store this provider writes, for a repository that holds
61
+ #: several datasets side by side (one per group). None writes the root.
62
+ group: str | None = None
63
+
64
+ #: Guard the process step with a memory ceiling. Set False for providers that manage
65
+ #: their own memory, such as the virtualized ingests.
66
+ #: True for a provider whose own writer names the variables (it writes several stores,
67
+ #: or writes raw values); the shared hook then leaves the dataset alone.
68
+ names_in_writer: bool = False
69
+ guard_memory: bool = True
70
+
71
+ #: Coordinates that must match the store exactly before an append. Override to add the
72
+ #: ones a dataset actually carries — ``step`` for a forecast, ``station`` for a station
73
+ #: table, a projected ``x``/``y`` for a radar grid. Providers previously reimplemented
74
+ #: :meth:`write_to_icechunk` solely to pass this through.
75
+ alignment_coords: tuple[str, ...] = ALIGNMENT_COORDS
76
+
77
+ def __init__(self, config: Config | None = None):
78
+ """Build a provider, using ``config`` or else the process-wide configuration."""
79
+ self._config = config
80
+ self._repo: icechunk.Repository | None = None
81
+
82
+ @property
83
+ def config(self) -> Config:
84
+ """Configuration for this provider, defaulting to the process-wide config."""
85
+ return self._config if self._config is not None else get_config()
86
+
87
+ @property
88
+ def store_path(self) -> str:
89
+ """Fully resolved store location, for logging and diagnostics."""
90
+ return self.config.store_path(self.store_prefix)
91
+
92
+ @abstractmethod
93
+ def fetch(self, it: pd.Timestamp, temp_dir: pathlib.Path | None = None, **kwargs) -> List[str]:
94
+ """Return input URIs or local paths for the given partition timestamp.
95
+
96
+ Return an empty list when nothing is available for the partition; that is treated
97
+ as "nothing to do", not as a failure.
98
+ """
99
+
100
+ @abstractmethod
101
+ def process(
102
+ self,
103
+ input_files: List[str],
104
+ it: pd.Timestamp,
105
+ temp_dir: pathlib.Path | None = None,
106
+ **kwargs,
107
+ ) -> xr.Dataset:
108
+ """Turn the fetched inputs into a dataset ready to write."""
109
+
110
+ def get_icechunk_repo(self) -> icechunk.Repository:
111
+ """Open or create the repository this provider writes to.
112
+
113
+ The handle is cached: a backfill of one day can be ~96 partitions, and reopening
114
+ the store for each one is pure overhead.
115
+ """
116
+ if self._repo is None:
117
+ self._repo = self.config.icechunk_repo(
118
+ self.store_prefix, config=self.repository_config()
119
+ )
120
+ return self._repo
121
+
122
+ def repository_config(self) -> icechunk.RepositoryConfig | None:
123
+ """Repository settings for the handle :meth:`get_icechunk_repo` opens.
124
+
125
+ None keeps the repository's own. Override for, e.g., manifest splitting.
126
+ """
127
+ return None
128
+
129
+ def missing_timesteps(self, desired: pd.DatetimeIndex) -> List[pd.Timestamp]:
130
+ """Return the timesteps in ``desired`` that are not yet stored."""
131
+ return _missing_timesteps(
132
+ self.get_icechunk_repo(), list(desired), append_dim=self.append_dim
133
+ )
134
+
135
+ def appendable(self, start: pd.Timestamp) -> bool:
136
+ """True when the store would still accept a partition starting at ``start``.
137
+
138
+ Partitions may arrive in any order, so the only one refused is one already stored.
139
+ This used to also refuse anything at or before the store's last step, because the
140
+ writer could only append in time order; it now appends out of order and the axis
141
+ is sorted afterwards by the store's reorder asset, so an hour behind the end is
142
+ ordinary work rather than a permanent gap. Staging pipelines check this before
143
+ downloading a partition.
144
+ """
145
+ return bool(self.missing_timesteps(pd.DatetimeIndex([to_naive_utc(start)])))
146
+
147
+ def axis_sorted(self) -> bool:
148
+ """True when the store's append axis is in order.
149
+
150
+ False after an out-of-order write — a backfill partition that ran behind one
151
+ already stored, or a provider revisiting an hour the upstream archive was still
152
+ filling in. The data is correct either way; until :meth:`sort_axis` runs, a
153
+ ``.sel`` over a *slice* of the store is unreliable.
154
+ """
155
+ return axis_is_sorted(self.get_icechunk_repo(), append_dim=self.append_dim)
156
+
157
+ def sort_axis(self) -> bool:
158
+ """Put the store's append axis back in order. Returns True if it changed.
159
+
160
+ Remaps chunks onto their sorted positions by rewriting the manifest, so it costs
161
+ the same whether the store holds a day or a decade.
162
+
163
+ **Nothing else may be writing to the store while this runs.** It moves chunks, so
164
+ a concurrent writer that had already looked up a position would write to the wrong
165
+ one. It is deliberately not called from :meth:`run_partition`: in Dagster it is the
166
+ separate ``<name>-reorder`` asset, which shares the ingest's concurrency pool so
167
+ the two cannot overlap, and which a human materialises when a backfill is done.
168
+ """
169
+ return _sort_append_axis(self.get_icechunk_repo(), append_dim=self.append_dim)
170
+
171
+ #: Mantissa bits to keep in floating point fields, or None to store them exactly. See
172
+ #: :func:`~planetary_datasets.common.store.bitround`. Declared per provider because
173
+ #: what is negligible depends on the quantity: 12 bits is a part in 4096, which is
174
+ #: below model precision for most geophysical fields and a large saving on disk.
175
+ keepbits: int | None = None
176
+
177
+ #: Substrings of variable names that are never rounded, whatever :attr:`keepbits` says.
178
+ #: For quantities where the loss is not negligible however small it looks: a wind
179
+ #: component is differenced with its partner to get a direction, so an error that is
180
+ #: tiny next to the wind speed is not tiny next to the difference, and a pressure sits
181
+ #: on a large offset where a *relative* precision of one in 4096 is tens of pascals.
182
+ keepbits_exact: tuple[str, ...] = ()
183
+
184
+ #: Explicit per-variable overrides, by exact name. Consulted before :attr:`keepbits`.
185
+ keepbits_by_variable: dict[str, int | None] = {}
186
+
187
+ #: Per-variable encoding applied when the store is created, merged over the default
188
+ #: compression. For keeping a packed integer source packed rather than storing it as
189
+ #: the floats it decodes to. Has no effect on a store that already exists.
190
+ encoding_overrides: dict[str, dict] = {}
191
+
192
+ def keepbits_for(self, variable: str) -> int | None:
193
+ """Mantissa bits to keep for one variable, or None to store it exactly."""
194
+ if variable in self.keepbits_by_variable:
195
+ return self.keepbits_by_variable[variable]
196
+ if any(pattern in variable for pattern in self.keepbits_exact):
197
+ return None
198
+ return self.keepbits
199
+
200
+ def prepare_for_write(self, processed: xr.Dataset) -> xr.Dataset:
201
+ """Last chance to reshape a dataset before it is written.
202
+
203
+ Applies :meth:`keepbits_for` per variable when rounding is configured. Override to
204
+ rechunk or reorder; call ``super().prepare_for_write(...)`` from the override to
205
+ keep the rounding.
206
+ """
207
+ if self.keepbits is not None or self.keepbits_by_variable:
208
+ processed = _bitround_dataset(processed, self.keepbits_for)
209
+ return processed
210
+
211
+ def write_to_icechunk(self, repo: icechunk.Repository, processed: xr.Dataset) -> bool:
212
+ """Write a processed dataset.
213
+
214
+ Most providers should set :attr:`alignment_coords` or override
215
+ :meth:`prepare_for_write` rather than replacing this.
216
+ """
217
+ return _write_to_icechunk(
218
+ repo,
219
+ self.prepare_for_write(processed),
220
+ append_dim=self.append_dim,
221
+ # atleast_1d: a provider may hand back a scalar append coordinate, which the
222
+ # writer itself tolerates.
223
+ message=f"{self.name}: {np.atleast_1d(processed[self.append_dim].values)[0]}",
224
+ alignment_coords=self.alignment_coords,
225
+ encoding_overrides=self.encoding_overrides,
226
+ group=self.group,
227
+ )
228
+
229
+ @staticmethod
230
+ @contextlib.contextmanager
231
+ def local_tempdir() -> Iterator[pathlib.Path]:
232
+ """Yield a temporary directory that is removed on exit.
233
+
234
+ This is a context manager rather than a plain function: returning the path of a
235
+ bare ``TemporaryDirectory`` lets it be finalised as soon as the reference goes out
236
+ of scope, deleting the directory while the caller still expects it to exist.
237
+ """
238
+ with tempfile.TemporaryDirectory(prefix="planetary-datasets-") as td:
239
+ yield pathlib.Path(td)
240
+
241
+ def run_partition(self, it: pd.Timestamp, check_present: bool = True) -> bool:
242
+ """Fetch, process and write one partition.
243
+
244
+ Returns True if data was written, False if there was nothing to do. This is the
245
+ method Dagster assets call.
246
+
247
+ Args:
248
+ it: Partition timestamp.
249
+ check_present: Skip the "already stored?" query. :meth:`run_range` sets this
250
+ False because it has already filtered the timestamps.
251
+ """
252
+ repo = self.get_icechunk_repo()
253
+
254
+ if check_present and not self.missing_timesteps(pd.DatetimeIndex([it])):
255
+ logger.debug(f"{self.name}: {it} already in {self.describe_store()}, skipping")
256
+ return False
257
+
258
+ with self.local_tempdir() as temp_dir:
259
+ input_files = self.fetch(it, temp_dir=temp_dir)
260
+ if not input_files:
261
+ logger.debug(f"{self.name}: no input files for {it}, skipping")
262
+ return False
263
+
264
+ logger.info(f"{self.name}: processing {len(input_files)} file(s) for {it}")
265
+ if self.guard_memory:
266
+ # memory_guard raises on exit, so the commit stays outside it: a breach
267
+ # then prevents the write instead of following it.
268
+ with memory_guard(what=f"{self.name} {it}"):
269
+ processed = self.process(input_files, it, temp_dir=temp_dir)
270
+ require_dataset_fits(processed, what=f"{self.name} {it}")
271
+ else:
272
+ processed = self.process(input_files, it, temp_dir=temp_dir)
273
+
274
+ target = self.store_for(processed, repo)
275
+ return self.write_to_icechunk(target, self.prepare_names(processed, target))
276
+
277
+ def prepare_names(self, processed: xr.Dataset, repo: icechunk.Repository) -> xr.Dataset:
278
+ """``processed`` named, and in units, as this provider's store keeps them.
279
+
280
+ See :func:`planetary_datasets.common.naming.prepare_for_store`. Taken after
281
+ :meth:`store_for`, which may roll the store to a new generation. The dataset as the
282
+ provider made it stays on ``self.source_processed`` for writers with a second store.
283
+ """
284
+ self.source_processed = processed
285
+ if self.names_in_writer:
286
+ return processed
287
+ return naming.prepare_for_store(
288
+ processed,
289
+ self.store_prefix,
290
+ naming.stored_arrays(repo, self.group),
291
+ group=self.group,
292
+ )
293
+
294
+ def describe_store(self) -> str:
295
+ """Where this provider's data lives, for a log line.
296
+
297
+ Its own store, for most providers. Overridden where "the store" is not one place:
298
+ a provider that picks between generations has to name the ones it actually looked
299
+ in, or a skip reads as though it came from a store that was never consulted.
300
+ """
301
+ return self.store_path
302
+
303
+ def store_for(self, processed: xr.Dataset, repo: icechunk.Repository):
304
+ """The repository ``processed`` should be written to.
305
+
306
+ A hook, taken after the partition has been processed rather than before, so that a
307
+ provider may choose its store from the *shape* of what it is about to write. The
308
+ default ignores ``processed`` and keeps the repository opened at the top of
309
+ :meth:`run_partition`; see
310
+ :class:`~planetary_datasets.common.generations.GenerationalStoreMixin`, which uses
311
+ this to roll a store forward when an upstream model is upgraded.
312
+ """
313
+ return repo
314
+
315
+ def run_range(self, timestamps: pd.DatetimeIndex) -> int:
316
+ """Run every missing partition in ``timestamps``. Returns the number written.
317
+
318
+ A failure on one partition is logged and does not stop the rest, matching how the
319
+ original scripts behaved over archive gaps.
320
+ """
321
+ written = 0
322
+ # Filter once here rather than re-reading the time coordinate per partition.
323
+ for it in self.missing_timesteps(timestamps):
324
+ try:
325
+ if self.run_partition(it, check_present=False):
326
+ written += 1
327
+ except Exception as exc: # noqa: BLE001 - one bad partition must not stop a backfill
328
+ logger.exception(f"{self.name}: partition {it} failed: {exc}")
329
+ return written
@@ -0,0 +1,40 @@
1
+ """Helpers shared by the data providers.
2
+
3
+ These were copy-pasted across dozens of standalone scripts before consolidation; the
4
+ canonical versions now live here. Import from this package rather than re-implementing:
5
+
6
+ * :mod:`planetary_datasets.common.download` — retrying downloads, skip-if-present.
7
+ * :mod:`planetary_datasets.common.dataset` — precision reduction, coordinate normalisation.
8
+ * :mod:`planetary_datasets.common.store` — icechunk encoding and append-or-create writes.
9
+ """
10
+
11
+ from planetary_datasets.common.dataset import (
12
+ make_lat_lon_coords_consistent,
13
+ make_spatial_coords_increasing,
14
+ lon_to_m180,
15
+ reduce_precision,
16
+ )
17
+ from planetary_datasets.common.download import download_many, download_one
18
+ from planetary_datasets.common.store import (
19
+ axis_is_sorted,
20
+ build_encoding,
21
+ existing_times,
22
+ has_timestep,
23
+ sort_append_axis,
24
+ write_to_icechunk,
25
+ )
26
+
27
+ __all__ = [
28
+ "axis_is_sorted",
29
+ "build_encoding",
30
+ "download_many",
31
+ "download_one",
32
+ "existing_times",
33
+ "has_timestep",
34
+ "lon_to_m180",
35
+ "make_lat_lon_coords_consistent",
36
+ "make_spatial_coords_increasing",
37
+ "reduce_precision",
38
+ "sort_append_axis",
39
+ "write_to_icechunk",
40
+ ]
@@ -0,0 +1,143 @@
1
+ """Dataset shaping helpers shared by the providers.
2
+
3
+ ``reduce_precision`` was duplicated in seven scripts; the coordinate helpers were copied
4
+ from ``ocf_data_sampler/load/utils.py`` into five more.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+ import xarray as xr
11
+ from loguru import logger
12
+
13
+ # Variables matching these substrings do not carry meaningful precision beyond float16 and
14
+ # dominate store size, so they are downcast before writing.
15
+ DEFAULT_LOW_PRECISION_HINTS = ("wind", "fraction", "temperature")
16
+
17
+
18
+ def reduce_precision(
19
+ ds: xr.Dataset,
20
+ hints: tuple[str, ...] = DEFAULT_LOW_PRECISION_HINTS,
21
+ dtype: str = "float16",
22
+ ) -> xr.Dataset:
23
+ """Downcast variables whose names match ``hints`` to ``dtype``.
24
+
25
+ Returns a new dataset; the input is not modified.
26
+ """
27
+ out = ds.copy()
28
+ for var in out.data_vars:
29
+ if any(hint in str(var) for hint in hints):
30
+ out[var] = out[var].astype(dtype)
31
+ return out
32
+
33
+
34
+ def lon_to_m180(ds: xr.Dataset, lon_name: str = "longitude") -> xr.Dataset:
35
+ """Convert a 0-360 longitude coordinate to -180-180 and sort ascending."""
36
+ if lon_name not in ds.coords:
37
+ return ds
38
+ ds = ds.assign_coords({lon_name: ((ds[lon_name] + 180) % 360) - 180})
39
+ return ds.sortby(lon_name)
40
+
41
+
42
+ def make_spatial_coords_increasing(
43
+ ds: xr.Dataset,
44
+ lat_name: str = "latitude",
45
+ lon_name: str = "longitude",
46
+ ) -> xr.Dataset:
47
+ """Sort latitude and longitude into ascending order if present."""
48
+ for name in (lat_name, lon_name):
49
+ if name in ds.coords and ds[name].ndim == 1 and ds[name].size > 1:
50
+ values = ds[name].values
51
+ if values[0] > values[-1]:
52
+ ds = ds.sortby(name)
53
+ return ds
54
+
55
+
56
+ def make_lat_lon_coords_consistent(
57
+ ds: xr.Dataset,
58
+ lat_name: str = "latitude",
59
+ lon_name: str = "longitude",
60
+ ) -> xr.Dataset:
61
+ """Normalise spatial coordinates so datasets from different sources can be concatenated.
62
+
63
+ Longitudes are put on -180-180 and both axes sorted ascending. Appending to an existing
64
+ icechunk store fails if the coordinate order differs, which is what this prevents.
65
+ """
66
+ ds = lon_to_m180(ds, lon_name=lon_name)
67
+ return make_spatial_coords_increasing(ds, lat_name=lat_name, lon_name=lon_name)
68
+
69
+
70
+ def sort_vertical_coords(
71
+ ds: xr.Dataset,
72
+ level_name: str = "level",
73
+ height_name: str = "height",
74
+ ) -> xr.Dataset:
75
+ """Sort pressure levels descending and heights ascending, when those dims exist."""
76
+ if level_name in ds.coords:
77
+ ds = ds.sortby(level_name, ascending=False)
78
+ if height_name in ds.coords:
79
+ ds = ds.sortby(height_name, ascending=True)
80
+ return ds
81
+
82
+
83
+ def rename_vars_by_long_name(ds: xr.Dataset, suffix: str = "") -> xr.Dataset:
84
+ """Rename data variables to their ``long_name`` attribute, slugified.
85
+
86
+ GRIB shortnames collide between level types, so several providers rename by long name
87
+ and append a suffix such as ``_at_surface`` to keep them distinct.
88
+ """
89
+ renames: dict[str, str] = {}
90
+ taken: set[str] = set()
91
+ for var in ds.data_vars:
92
+ long_name = str(ds[var].attrs.get("long_name", var))
93
+ slug = long_name.lower().replace(" ", "_").replace("(", "").replace(")", "")
94
+ target = f"{slug}{suffix}"
95
+ if target in taken:
96
+ # Two variables can share a long_name (GRIB does this across level types).
97
+ # Renaming both to it would raise, so keep the original name for the later one.
98
+ logger.debug(f"long_name {target!r} already used, keeping {var!r} unchanged")
99
+ target = str(var)
100
+ # Falling back to the original name is not always enough: an earlier variable may
101
+ # already have been renamed onto exactly this variable's name, and `ds.rename`
102
+ # rejects the resulting collision outright. Disambiguate rather than leaving two
103
+ # variables pointed at one name.
104
+ if target in taken:
105
+ base = target
106
+ n = 2
107
+ while target in taken:
108
+ target = f"{base}_{n}"
109
+ n += 1
110
+ logger.debug(f"{base!r} is taken as well, renaming {var!r} to {target!r}")
111
+ taken.add(target)
112
+ renames[str(var)] = target
113
+ return ds.rename(renames)
114
+
115
+
116
+ def _values_equal(x: np.ndarray, y: np.ndarray) -> bool:
117
+ """Elementwise equality that treats NaN as equal to NaN.
118
+
119
+ Station rosters carry NaN latitude/longitude for entries whose position the upstream
120
+ metadata does not give (ISD's ``isd-history.csv`` leaves LAT/LON blank for hundreds of
121
+ stations). Plain ``array_equal`` reports such a coordinate as different from itself, so
122
+ the alignment guard would reject every append after the store was created.
123
+ """
124
+ if x.shape != y.shape:
125
+ return False
126
+ if np.issubdtype(x.dtype, np.inexact) and np.issubdtype(y.dtype, np.inexact):
127
+ return bool(np.array_equal(x, y, equal_nan=True))
128
+ return bool(np.array_equal(x, y))
129
+
130
+
131
+ def coords_match(a: xr.Dataset, b: xr.Dataset, coords: tuple[str, ...]) -> tuple[bool, str | None]:
132
+ """Check that shared coordinates are identical between two datasets.
133
+
134
+ Returns ``(True, None)`` when they match, otherwise ``(False, name)`` naming the first
135
+ coordinate that differs.
136
+ """
137
+ for coord in coords:
138
+ # Coords, not dims: geostationary lat/lon are 2-D non-dimension coordinates, and
139
+ # keying on dims meant the guard never fired for them.
140
+ if coord in a.coords and coord in b.coords:
141
+ if not _values_equal(a[coord].values, b[coord].values):
142
+ return False, coord
143
+ return True, None