grib2io.kerchunk
Kerchunk Reference Manifest Generator
Provides ReferenceGenerator, which scans one or more GRIB2 files
using grib2io's build_index() infrastructure and produces a
Kerchunk v1 reference manifest
mapping Zarr chunk keys to [url, offset, length] tuples within the
original files.
The manifest can be serialized to JSON or Parquet and later opened with
fsspec.filesystem("reference") to create a virtual Zarr store that
reads data lazily from the original GRIB2 bytes, decoded on-the-fly by
grib2io.codecs.Grib2Codec.
Example
>>> from grib2io.kerchunk import ReferenceGenerator
>>> gen = ReferenceGenerator("gfs.grib2")
>>> manifest = gen.generate()
>>> gen.to_json("gfs_refs.json")
1""" 2Kerchunk Reference Manifest Generator 3====================================== 4 5Provides :class:`ReferenceGenerator`, which scans one or more GRIB2 files 6using grib2io's :func:`build_index` infrastructure and produces a 7`Kerchunk v1 reference manifest <https://fsspec.github.io/kerchunk/spec>`_ 8mapping Zarr chunk keys to ``[url, offset, length]`` tuples within the 9original files. 10 11The manifest can be serialized to JSON or Parquet and later opened with 12``fsspec.filesystem("reference")`` to create a virtual Zarr store that 13reads data lazily from the original GRIB2 bytes, decoded on-the-fly by 14:class:`grib2io.codecs.Grib2Codec`. 15 16Example 17------- 18>>> from grib2io.kerchunk import ReferenceGenerator 19>>> gen = ReferenceGenerator("gfs.grib2") 20>>> manifest = gen.generate() 21>>> gen.to_json("gfs_refs.json") 22""" 23 24from __future__ import annotations 25 26import base64 27import json 28import logging 29import os 30import re 31import warnings 32from urllib.parse import urlparse 33from typing import Any, Dict, List, Optional, Set, Union 34 35import numpy as np 36 37import grib2io 38 39_logger = logging.getLogger(__name__) 40 41 42# --------------------------------------------------------------------------- 43# Lazy import guards 44# --------------------------------------------------------------------------- 45 46 47def _ensure_kerchunk(): 48 """Raise ``ImportError`` if *kerchunk* is not available.""" 49 try: 50 import kerchunk # noqa: F401 51 except ImportError: 52 raise ImportError("kerchunk is required for reference generation. Install with: pip install grib2io[kerchunk]") 53 54 55def _ensure_numcodecs(): 56 """Raise ``ImportError`` if *numcodecs* is not available.""" 57 try: 58 import numcodecs # noqa: F401 59 except ImportError: 60 raise ImportError("numcodecs is required for the GRIB2 codec. Install with: pip install grib2io[kerchunk]") 61 62 63# --------------------------------------------------------------------------- 64# Dimension names used for grouping (mirrors xarray_backend logic) 65# --------------------------------------------------------------------------- 66 67# These are the non-geographic dimensions that can appear in GRIB2 data. 68# The order here determines the dimension order in the Zarr array 69# (before the trailing y, x spatial dims). 70_ORDERED_DIM_NAMES = [ 71 "valid_time", 72 "perturbationNumber", 73 "duration", 74 "percentileValue", 75 "level", 76] 77 78# These dims are always emitted (even at size 1) so that manifests from 79# different files can be concatenated along them without shape errors. 80_ALWAYS_INCLUDE_DIMS = frozenset({"valid_time"}) 81 82# Lazy-loaded level name mapping (typeOfFirstFixedSurface int -> (name, source)) 83_LEVEL_NAME_MAPPING: Optional[dict] = None 84 85 86def _get_level_name_mapping() -> dict: 87 global _LEVEL_NAME_MAPPING 88 if _LEVEL_NAME_MAPPING is None: 89 _LEVEL_NAME_MAPPING = grib2io.tables.get_table("4.5.grib2io.level.name") 90 return _LEVEL_NAME_MAPPING 91 92 93def _level_dim_name(msg) -> str: 94 """Return a surface-type-specific level dimension name. 95 96 Mirrors the xarray backend's ``swap_dims({"level": key})`` logic so 97 variables at different surface types get distinct dimension names 98 (e.g. ``isobaric_surface``, ``height_above_ground``) and can 99 coexist in a single flat xarray Dataset without conflicting sizes. 100 """ 101 toffs = getattr(msg, "typeOfFirstFixedSurface", None) 102 if toffs is None: 103 return "level" 104 val = toffs.value if hasattr(toffs, "value") else int(toffs) 105 entry = _get_level_name_mapping().get(int(val)) 106 if entry: 107 return entry[0] # e.g. 'isobaric_surface', 'height_above_ground' 108 return "level" 109 110 111# --------------------------------------------------------------------------- 112# Public API 113# --------------------------------------------------------------------------- 114 115 116class ReferenceGenerator: 117 """Generate Kerchunk v1 reference manifests from GRIB2 files. 118 119 Parameters 120 ---------- 121 file_paths : str or list of str 122 One or more GRIB2 file paths (local paths or URIs). 123 filters : dict, optional 124 Filter GRIB2 messages by metadata attributes. Keys can be any 125 ``Grib2Message`` attribute name (e.g. ``shortName``, ``leadTime``). 126 storage_options : dict, optional 127 Extra options passed to ``fsspec.open`` for remote URIs 128 (e.g. ``{"anon": True}`` for public S3 buckets). 129 validate : bool, default True 130 Check the finished manifest for internal consistency before returning 131 it, and raise :class:`ValueError` if any variable's dimension lengths 132 disagree with the coordinate arrays it references. Pass ``False`` to 133 emit the manifest regardless. 134 """ 135 136 def __init__( 137 self, 138 file_paths: Union[str, List[str]], 139 filters: Optional[Dict[str, Any]] = None, 140 storage_options: Optional[Dict[str, Any]] = None, 141 max_workers: Optional[int] = None, 142 validate: bool = True, 143 ): 144 _ensure_numcodecs() 145 146 if isinstance(file_paths, (str, os.PathLike)): 147 file_paths = [str(file_paths)] 148 else: 149 file_paths = [str(p) for p in file_paths] 150 151 # Validate file accessibility. 152 # Local filesystem paths must exist. URI inputs are handled by 153 # grib2io.open/fsspec at scan time and should not be rejected here. 154 for fp in file_paths: 155 if _is_local_path(fp) and not os.path.isfile(fp): 156 raise FileNotFoundError(f"GRIB2 file not found: {fp}") 157 158 self.file_paths = file_paths 159 self.filters = filters or {} 160 self.storage_options = storage_options or {} 161 self.max_workers = max_workers 162 self.validate = validate 163 self._manifest: Optional[dict] = None 164 165 def generate(self) -> dict: 166 """Scan files and produce a Kerchunk v1 reference manifest. 167 168 Returns 169 ------- 170 dict 171 Kerchunk reference spec v1 dict with keys ``"version"`` and 172 ``"refs"``. 173 """ 174 refs: Dict[str, Any] = {} 175 176 # .zgroup at root 177 refs[".zgroup"] = json.dumps({"zarr_format": 2}) 178 179 # Collect all messages across files, keyed by variable group 180 # group_key = (shortName, typeOfFirstFixedSurface, pdtn, typeOfSecondFixedSurface, probability_key) 181 # This ensures messages with different surface types are not mixed. 182 all_var_messages: Dict[tuple, list] = {} 183 184 n_files = len(self.file_paths) 185 use_parallel = self.max_workers != 1 and n_files > 1 and not _is_local_path(self.file_paths[0]) 186 187 if use_parallel: 188 import concurrent.futures 189 190 workers = self.max_workers or min(n_files, 8) 191 192 def _scan_one(file_path): 193 file_uri = _file_uri(file_path) 194 local_msgs: Dict[tuple, list] = {} 195 self._scan_file(file_path, file_uri, local_msgs) 196 return local_msgs 197 198 with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: 199 futures = {pool.submit(_scan_one, fp): fp for fp in self.file_paths} 200 for future in concurrent.futures.as_completed(futures): 201 fp = futures[future] 202 try: 203 local_msgs = future.result() 204 for key, entries in local_msgs.items(): 205 all_var_messages.setdefault(key, []).extend(entries) 206 except Exception as e: 207 raise ValueError(f"Failed to parse GRIB2 file '{fp}': {e}") from e 208 else: 209 for file_path in self.file_paths: 210 file_uri = _file_uri(file_path) 211 try: 212 self._scan_file(file_path, file_uri, all_var_messages) 213 except Exception as e: 214 raise ValueError(f"Failed to parse GRIB2 file '{file_path}': {e}") from e 215 216 # For each variable group, map messages to dimensions and build refs. 217 # Track used variable names to handle collisions (same shortName 218 # but different surface types). 219 # Also track level coord name -> level values so that the same surface 220 # type but different level extents get disambiguated names (mirrors 221 # how the xarray backend keeps each surface type in its own Dataset). 222 used_var_names: Dict[str, int] = {} 223 # Emitted dimension name -> coordinate values written under it. Shared 224 # across every variable so that two variables needing different values 225 # for the same dimension get distinct names instead of one silently 226 # overwriting the other's coordinate array. 227 dim_coord_registry: Dict[str, list] = {} 228 for group_key, msg_entries in all_var_messages.items(): 229 var_name = group_key[0] # shortName is the first element 230 # Probability products are named for their threshold so each one 231 # is self-describing, e.g. PTYPE_prob_between_1p0_and_2p0. 232 prob_key = group_key[4] 233 if prob_key is not None: 234 var_name = f"{var_name}_{_probability_suffix(prob_key)}" 235 if var_name in used_var_names: 236 used_var_names[var_name] += 1 237 zarr_var_name = f"{var_name}_{used_var_names[var_name]}" 238 else: 239 used_var_names[var_name] = 0 240 zarr_var_name = var_name 241 self._build_variable_refs(zarr_var_name, msg_entries, refs, dim_coord_registry) 242 243 # Build latitude/longitude coordinate arrays from the grid definition. 244 # All messages are assumed to share the same grid (required by the 245 # xarray backend too), so we use the first available message. 246 if all_var_messages: 247 first_entries = next(iter(all_var_messages.values())) 248 rep_msg = first_entries[0].msg 249 _build_latlon_coord_refs(rep_msg, refs) 250 251 # Root-level dataset metadata (CF global attributes + GRIB2 252 # provenance from Sections 0/1/4). Without this, a manifest 253 # separated from its filename carries no record of which model, 254 # center, or cycle it describes. 255 refs[".zattrs"] = json.dumps(_build_root_zattrs(rep_msg)) 256 257 if self.validate: 258 problems = _validate_refs(refs) 259 if problems: 260 raise ValueError(_format_validation_errors(problems)) 261 262 self._manifest = {"version": 1, "refs": refs} 263 return self._manifest 264 265 def to_json(self, output_path: str) -> None: 266 """Serialize the manifest to a JSON file. 267 268 Parameters 269 ---------- 270 output_path : str 271 Path to the output JSON file. 272 """ 273 if self._manifest is None: 274 self.generate() 275 with open(output_path, "w") as f: 276 json.dump(self._manifest, f) 277 278 def to_parquet(self, output_path: str) -> None: 279 """Serialize the manifest to a Parquet reference store. 280 281 Parameters 282 ---------- 283 output_path : str 284 Path to the output Parquet directory. 285 """ 286 _ensure_kerchunk() 287 if self._manifest is None: 288 self.generate() 289 290 import fsspec 291 from fsspec.implementations.reference import LazyReferenceMapper 292 293 fs, _ = fsspec.core.url_to_fs(output_path) 294 out = LazyReferenceMapper.create(output_path, fs=fs, record_size=100_000, engine="pyarrow") 295 refs = self._manifest.get("refs", self._manifest) 296 for k in sorted(refs): 297 out[k] = refs[k] 298 out.flush() 299 300 # ------------------------------------------------------------------ 301 # Internal scanning 302 # ------------------------------------------------------------------ 303 304 def _build_remote_index_filtered( 305 self, 306 file_path: str, 307 shortname_filter: Optional[Union[str, Set[str]]] = None, 308 scan_storage_options: Optional[dict] = None, 309 ): 310 """Build a GRIB2 index for a remote file using sidecar pre-filtering. 311 312 Works with any combination of filters: a ``shortName`` alone, 313 ``shortName`` plus additional filters (e.g. ``typeOfFirstFixedSurface`` 314 / ``level``), or filters without a ``shortName`` at all. 315 316 Instead of fetching headers for every message (~700 HTTP requests for a 317 full GFS 0.25° file), this method: 318 319 1. Checks grib2io's local cache – if the full or filtered index was 320 saved from a previous run, it loads it instantly. 321 2. Checks for a remote grib2io ``.grib2ioidx`` sidecar (binary index) 322 alongside the GRIB2 file — the most efficient format, containing 323 pre-parsed section offsets and avoiding header reads entirely. 324 3. Fetches the wgrib2 ``.idx`` text sidecar and keeps only the byte 325 offsets whose shortName matches the filter, reducing HTTP range 326 requests from ~700 to ~1–50. 327 4. Saves the partial index to a filter-specific cache key so the next 328 call for the same file+filter is also instant. 329 5. Falls back to ``grib2io.open`` (full index, slow on first call) if 330 no sidecar is available. 331 332 Returns 333 ------- 334 tuple(dict, list) 335 ``(index, msgs)`` where *index* is a grib2io index dict and *msgs* 336 is a list of :class:`~grib2io.Grib2Message` objects. 337 """ 338 import builtins 339 import hashlib 340 import pickle 341 342 import fsspec 343 344 from grib2io._grib2io import build_index 345 from grib2io import msgs_from_index 346 347 scan_storage_options = scan_storage_options or {} 348 cache_root = os.path.join(os.path.expanduser("~"), ".cache", "grib2io") 349 350 # Open the remote file to obtain its size (one lightweight HEAD/info call). 351 # For the filtered fast-path we override cache settings: "readahead" with 352 # a small block size means consecutive section-header reads within the same 353 # message share one HTTP range request instead of each triggering a new one. 354 fh_options = dict(scan_storage_options) 355 fh_options["default_cache_type"] = "readahead" 356 fh_options["default_block_size"] = 4096 357 fh = fsspec.open(file_path, "rb", **fh_options).open() 358 try: 359 size = int(fh.info().get("size", 0) or 0) 360 except Exception: 361 size = 0 362 363 # ------------------------------------------------------------------ # 364 # 1. Full-index cache (populated by unfiltered grib2io.open calls) # 365 # ------------------------------------------------------------------ # 366 full_cache_key = hashlib.sha1((file_path + str(size)).encode("ASCII")).hexdigest() 367 full_cache_path = os.path.join(cache_root, f"{full_cache_key}.grib2ioidx") 368 if os.path.exists(full_cache_path): 369 with builtins.open(full_cache_path, "rb") as cf: 370 index = pickle.load(cf) 371 msgs = msgs_from_index(index, filehandle=fh) 372 fh.close() 373 return index, msgs 374 375 # ------------------------------------------------------------------ # 376 # 2. Filter-specific partial-index cache # 377 # ------------------------------------------------------------------ # 378 filter_repr = ":".join(f"{k}={v}" for k, v in sorted(self.filters.items())) 379 filtered_cache_key = hashlib.sha1((file_path + str(size) + ":" + filter_repr).encode("ASCII")).hexdigest() 380 filtered_cache_path = os.path.join(cache_root, f"{filtered_cache_key}.grib2ioidx") 381 if os.path.exists(filtered_cache_path): 382 with builtins.open(filtered_cache_path, "rb") as cf: 383 index = pickle.load(cf) 384 msgs = msgs_from_index(index, filehandle=fh) 385 fh.close() 386 return index, msgs 387 388 # ------------------------------------------------------------------ # 389 # 3. Remote grib2io index sidecar (.grib2ioidx) # 390 # ------------------------------------------------------------------ # 391 # grib2io publishes its own binary index alongside the GRIB2 file. 392 # This is the most efficient index format — it contains the full 393 # parsed section offsets/sizes and avoids any header reads. Check 394 # for it before falling back to the wgrib2 text .idx sidecar. 395 grib2io_idx_url = file_path + ".grib2ioidx" 396 try: 397 with fsspec.open(grib2io_idx_url, "rb", **scan_storage_options) as gf: 398 index = pickle.load(gf) 399 msgs = msgs_from_index(index, filehandle=fh) 400 fh.close() 401 # Cache locally so subsequent calls are instant. 402 try: 403 os.makedirs(cache_root, exist_ok=True) 404 with builtins.open(full_cache_path, "wb") as cf: 405 pickle.dump(index, cf) 406 except Exception: 407 pass 408 return index, msgs 409 except Exception: 410 pass 411 412 # ------------------------------------------------------------------ # 413 # 4. wgrib2 .idx sidecar pre-filtering # 414 # ------------------------------------------------------------------ # 415 idx_url = file_path + ".idx" 416 idx_fetch_ok = False 417 filtered_offsets: List[int] = [] 418 try: 419 with fsspec.open(idx_url, "r", **scan_storage_options) as idxf: 420 filtered_offsets = _prefilter_idx_offsets(idxf, shortname_filter, self.filters) 421 idx_fetch_ok = True 422 except Exception: 423 pass 424 425 if idx_fetch_ok: 426 if not filtered_offsets: 427 # shortName simply does not appear in this file. 428 fh.close() 429 return {}, [] 430 index = build_index(fh, offsets=filtered_offsets) 431 msgs = msgs_from_index(index, filehandle=fh) 432 fh.close() 433 # Persist the partial index so the next call is instant. 434 try: 435 os.makedirs(cache_root, exist_ok=True) 436 with builtins.open(filtered_cache_path, "wb") as cf: 437 pickle.dump(index, cf) 438 except Exception: 439 pass 440 return index, msgs 441 442 # ------------------------------------------------------------------ # 443 # 5. Fall back: let grib2io.open build the full index (slow on first # 444 # call, but saves to grib2io's own cache for future calls). # 445 # ------------------------------------------------------------------ # 446 fh.close() 447 with grib2io.open(file_path, save_index=True, use_index=True, **scan_storage_options) as f: 448 return f._index, list(f) 449 450 def _scan_file( 451 self, 452 file_path: str, 453 file_uri: str, 454 all_var_messages: Dict[str, list], 455 ) -> None: 456 """Scan a single GRIB2 file and collect message entries.""" 457 if _is_local_path(file_path): 458 with grib2io.open(file_path, save_index=False, use_index=True) as f: 459 index = f._index 460 msgs = list(f) 461 else: 462 scan_storage_options = _remote_scan_storage_options(file_path, self.storage_options) 463 shortname_filter = self.filters.get("shortName") if self.filters else None 464 # Normalise list/tuple to a set so _prefilter_idx_offsets can do a 465 # fast membership test; leave scalar strings as-is. 466 if isinstance(shortname_filter, (list, tuple)): 467 shortname_filter = set(shortname_filter) 468 # Fast path: resolve the index from a sidecar (.grib2ioidx or the 469 # wgrib2 .idx) instead of fetching headers for every message. This 470 # works whether or not a shortName filter is given: when shortName 471 # is present it is combined with any other filters; when it is 472 # absent, other filters (e.g. typeOfFirstFixedSurface/level) are 473 # still applied to the .idx, and the .grib2ioidx sidecar yields the 474 # full parsed index with no header reads at all. 475 index, msgs = self._build_remote_index_filtered(file_path, shortname_filter, scan_storage_options) 476 477 n_msgs = len(msgs) 478 479 # GRIB2 submessages may omit Section 3 and inherit the grid definition 480 # of the message before them, so index["section3"] is not necessarily 481 # parallel to the message list and must not be indexed by the message 482 # counter. Resolve each message to its own Section 3 entry first. 483 sec3_map = _build_section3_map(index, n_msgs) 484 485 for i in range(n_msgs): 486 msg = msgs[i] 487 488 # Apply filters 489 if not self._matches_filters(msg): 490 continue 491 492 sec_offsets = index["sectionOffset"][i] 493 sec_sizes = index["sectionSize"][i] 494 bmapflag = index["bmapflag"][i] 495 496 # Section 7 offset and length 497 sec7_offset = sec_offsets[7] 498 sec7_length = sec_sizes[7] 499 500 # Section 5 (data representation) — always present 501 sec5_offset = sec_offsets[5] 502 sec5_length = sec_sizes[5] 503 504 # Section 6 (bitmap) — always present (6 bytes when no bitmap) 505 sec6_length = sec_sizes[6] 506 # Offset only needed for the old bitmap-conditional path (kept for reference) 507 sec6_offset = sec_offsets[6] if bmapflag in {0, 254} else None 508 509 # Build a composite variable key that includes the surface type 510 # to avoid grouping messages with different surface types together. 511 # This mirrors how the xarray backend requires filtering to a 512 # single typeOfFirstFixedSurface. 513 var_name = str(msg.shortName) 514 type_of_first_fixed_surface = msg.typeOfFirstFixedSurface 515 if hasattr(type_of_first_fixed_surface, "value"): 516 toffs_val = type_of_first_fixed_surface.value 517 else: 518 toffs_val = type_of_first_fixed_surface 519 520 # Also include typeOfGeneratingProcess and 521 # productDefinitionTemplateNumber to disambiguate further 522 # (same approach as xarray backend's required_uniques) 523 pdtn = msg.productDefinitionTemplateNumber 524 if hasattr(pdtn, "value"): 525 pdtn_val = pdtn.value 526 else: 527 pdtn_val = pdtn 528 529 type_of_second_fixed_surface = msg.typeOfSecondFixedSurface 530 if hasattr(type_of_second_fixed_surface, "value"): 531 tosfs_val = type_of_second_fixed_surface.value 532 else: 533 tosfs_val = type_of_second_fixed_surface 534 535 # Group key: shortName + surface type + pdtn + second surface type, 536 # plus the probability threshold for probability products. Those 537 # commonly share every other identifying field -- NBM PTYPE carries 538 # four messages that differ only in their category bounds -- so 539 # without the threshold they would collide into one variable. 540 group_key = (var_name, int(toffs_val), int(pdtn_val), int(tosfs_val), _probability_key(msg)) 541 542 entry = _MsgEntry( 543 msg=msg, 544 file_uri=file_uri, 545 sec5_offset=sec5_offset, 546 sec5_length=sec5_length, 547 sec6_length=sec6_length, 548 sec7_offset=sec7_offset, 549 sec7_length=sec7_length, 550 sec6_offset=sec6_offset, 551 bmapflag=bmapflag, 552 index_section3=index["section3"][sec3_map[i]], 553 index_section5=index["section5"][i], 554 ) 555 556 all_var_messages.setdefault(group_key, []).append(entry) 557 558 def _matches_filters(self, msg) -> bool: 559 """Check if a message matches all user-supplied filters. 560 561 Filter values may be: 562 563 * **scalar** – exact equality (``{"shortName": "TMP"}``) 564 * **list / tuple / set** – membership test 565 (``{"level": [500, 850, 250]}``) 566 * **slice** – inclusive range test 567 (``{"level": slice(500, 850)}``) 568 """ 569 for key, value in self.filters.items(): 570 msg_val = getattr(msg, key, None) 571 if msg_val is None: 572 return False 573 # Unwrap Grib2Metadata wrapper objects 574 if hasattr(msg_val, "value"): 575 msg_val = msg_val.value 576 if isinstance(value, slice): 577 lo = value.start if value.start is not None else float("-inf") 578 hi = value.stop if value.stop is not None else float("inf") 579 try: 580 if not (lo <= msg_val <= hi): 581 return False 582 except TypeError: 583 return False 584 elif isinstance(value, (list, tuple, set)): 585 if msg_val not in value: 586 return False 587 else: 588 if msg_val != value: 589 return False 590 return True 591 592 # ------------------------------------------------------------------ 593 # Variable reference building 594 # ------------------------------------------------------------------ 595 596 def _build_variable_refs( 597 self, 598 var_name: str, 599 msg_entries: list, 600 refs: Dict[str, Any], 601 dim_coord_registry: Optional[Dict[str, list]] = None, 602 ) -> None: 603 """Build all Zarr refs for a single variable.""" 604 # Derive surface-type-specific level dim name (mirrors xarray_backend). 605 level_base = _level_dim_name(msg_entries[0].msg) 606 dim_mapping = _map_messages_to_dimensions(msg_entries, level_dim_name=level_base) 607 608 dim_names = dim_mapping["dim_names"] # ordered, using base names 609 dim_values = dim_mapping["dim_values"] # base name -> sorted unique values 610 msg_index_map = dim_mapping["msg_index_map"] 611 duplicate_entry_indices = dim_mapping["duplicate_entry_indices"] 612 613 # Resolve every non-spatial dimension against the shared registry, not 614 # just the level one. Two variables can disagree on the extent of any 615 # of them -- NBM, for example, emits CWASP over 7 percentiles and CAPE 616 # over 3 -- and whichever is written second would otherwise overwrite 617 # the first's coordinate array, leaving the manifest unopenable. 618 rename = _resolve_dim_names(dim_names, dim_values, dim_coord_registry) 619 emitted = [rename[d] for d in dim_names] 620 621 # Representative message for metadata 622 rep_msg = msg_entries[0].msg 623 624 # Compute shape (ensure plain Python ints for JSON serialization) 625 shape = [len(dim_values[d]) for d in dim_names] + [int(rep_msg.ny), int(rep_msg.nx)] 626 chunks = [1] * len(dim_names) + [int(rep_msg.ny), int(rep_msg.nx)] 627 628 # Build .zarray 629 codec_config = _build_codec_config(msg_entries[0]) 630 zarray = _build_zarray_metadata(rep_msg, shape, chunks, codec_config) 631 refs[f"{var_name}/.zarray"] = json.dumps(zarray) 632 633 # Build .zattrs 634 dim_labels = emitted + ["y", "x"] 635 zattrs = _build_zattrs(rep_msg, dim_labels) 636 637 # ``level`` and ``valueOfFirstFixedSurface`` describe the representative 638 # message only. When several messages are folded into one array along a 639 # level dimension they are correct for the first level and wrong for 640 # every other one, so a consumer reading attributes instead of the 641 # coordinate array is misled (e.g. a 41-level pressure array labelled 642 # "0.01 mb"). Drop them here and let the level coordinate carry the 643 # information instead -- see _build_coord_refs / _level_coord_attrs. 644 n_levels = len(dim_values.get(level_base, ())) 645 if n_levels > 1: 646 for _key in ("level", "valueOfFirstFixedSurface"): 647 zattrs.pop(_key, None) 648 649 refs[f"{var_name}/.zattrs"] = json.dumps(zattrs) 650 651 # Build data chunk refs 652 for dim_tuple, entry_idx in msg_index_map.items(): 653 entry = msg_entries[entry_idx] 654 dim_indices = [] 655 for i, d in enumerate(dim_names): 656 val = dim_tuple[i] 657 idx = list(dim_values[d]).index(val) 658 dim_indices.append(idx) 659 660 chunk_key = _build_chunk_key(var_name, dim_indices) 661 662 # Store a combined reference covering sections 5+6+7 so that the 663 # codec can parse the per-chunk data representation template (sec5) 664 # and bitmap (sec6) dynamically. Sections 5, 6, and 7 are always 665 # contiguous in the GRIB2 byte stream. 666 refs[chunk_key] = [ 667 entry.file_uri, 668 entry.sec5_offset, 669 entry.sec5_length + entry.sec6_length + entry.sec7_length, 670 ] 671 672 # Build coordinate arrays as inline base64-encoded refs. The emitted 673 # name may be suffixed, so pass the base name too: the value encoding 674 # and CF attributes are chosen from what the dimension *is*, not from 675 # what it ended up being called. 676 for d in dim_names: 677 _build_coord_refs( 678 rename[d], 679 dim_values[d], 680 refs, 681 msg=rep_msg, 682 is_level=(d == level_base), 683 base_name=d, 684 ) 685 686 # Re-emit any messages whose identifying metadata exactly collided 687 # with an earlier message as a sibling variable, so no message's 688 # bytes are silently dropped from the manifest. smartinit, for 689 # example, encodes a 1-bit binary field whose PDT is byte-identical 690 # to the real surface TMP message; only the packing (Section 5) 691 # differs. Which message is "the" variable and which is the 692 # duplicate is file-order and cannot be determined from metadata, 693 # hence the warning telling consumers to inspect both. 694 if duplicate_entry_indices: 695 dup_entries = [msg_entries[i] for i in duplicate_entry_indices] 696 m = re.match(r"^(.*)_dup(\d*)$", var_name) 697 if m: 698 dup_name = f"{m.group(1)}_dup{int(m.group(2) or 1) + 1}" 699 else: 700 dup_name = f"{var_name}_dup" 701 warnings.warn( 702 f"{len(dup_entries)} message(s) share identical identifying " 703 f"metadata with an earlier '{var_name}' message; emitting " 704 f"them as '{dup_name}'. The GRIB2 encoding of these " 705 f"products is ambiguous; inspect both variables to " 706 f"determine which is the intended field." 707 ) 708 self._build_variable_refs(dup_name, dup_entries, refs, dim_coord_registry) 709 710 # ------------------------------------------------------------------ 711 # Manifest access 712 # ------------------------------------------------------------------ 713 714 @property 715 def manifest(self) -> Optional[dict]: 716 """The generated manifest, or ``None`` if :meth:`generate` has not 717 been called yet.""" 718 return self._manifest 719 720 721# --------------------------------------------------------------------------- 722# Internal data class for message entries 723# --------------------------------------------------------------------------- 724 725 726class _MsgEntry: 727 """Lightweight container for a scanned GRIB2 message.""" 728 729 __slots__ = ( 730 "msg", 731 "file_uri", 732 "sec5_offset", 733 "sec5_length", 734 "sec6_length", 735 "sec7_offset", 736 "sec7_length", 737 "sec6_offset", 738 "bmapflag", 739 "index_section3", 740 "index_section5", 741 ) 742 743 def __init__( 744 self, 745 msg, 746 file_uri: str, 747 sec5_offset: int, 748 sec5_length: int, 749 sec6_length: int, 750 sec7_offset: int, 751 sec7_length: int, 752 sec6_offset: Optional[int], 753 bmapflag: int, 754 index_section3: np.ndarray, 755 index_section5: np.ndarray, 756 ): 757 self.msg = msg 758 self.file_uri = file_uri 759 self.sec5_offset = sec5_offset 760 self.sec5_length = sec5_length 761 self.sec6_length = sec6_length 762 self.sec7_offset = sec7_offset 763 self.sec7_length = sec7_length 764 self.sec6_offset = sec6_offset 765 self.bmapflag = bmapflag 766 self.index_section3 = index_section3 767 self.index_section5 = index_section5 768 769 770# --------------------------------------------------------------------------- 771# Helper functions 772# --------------------------------------------------------------------------- 773 774 775def _file_uri(file_path: str) -> str: 776 """Convert a local file path to ``file://`` URI, preserving URI inputs.""" 777 if not _is_local_path(file_path): 778 return file_path 779 abs_path = os.path.abspath(file_path) 780 return f"file://{abs_path}" 781 782 783def _is_local_path(path: str) -> bool: 784 """Return ``True`` if *path* looks like a local filesystem path.""" 785 parsed = urlparse(path) 786 return parsed.scheme == "" 787 788 789def _build_section3_map(index: dict, n_msgs: int) -> List[int]: 790 """Map each message index onto its entry in ``index["section3"]``. 791 792 ``build_index`` appends to ``index["section3"]`` only when it actually 793 reads a Section 3. After a message ends, the trailer check reads the next 794 section number, which may be 2, 3, or 4: 795 796 * ``nextsec == 4`` — Sections 2 and 3 are not repeated and the submessage 797 inherits the preceding grid definition, so ``section3`` does not grow. 798 * ``nextsec == 3`` — Section 3 is re-read and appended, so it does grow. 799 * ``nextsec == 2`` — Section 2 repeats and Section 3 follows, so it grows. 800 801 ``_isSubmessage`` is set for all three, which is why a counter keyed on it 802 is only correct for the first case. ``sectionOffset[i][3]`` is deep-copied 803 per message and retains the previous Section 3 offset when a submessage 804 omits it, so distinct offsets in order of first appearance correspond 805 one-to-one with the appended Section 3 entries. Mapping through the offset 806 is therefore correct in all three cases. 807 808 Parameters 809 ---------- 810 index : dict 811 The grib2io file index. 812 n_msgs : int 813 Number of messages in the file. 814 815 Returns 816 ------- 817 list of int 818 ``sec3_map[i]`` is the index into ``index["section3"]`` for message 819 ``i``. Reduces to the identity mapping when no submessages are present. 820 """ 821 n_sec3 = len(index.get("section3", ())) 822 if n_sec3 == 0: 823 return [0] * n_msgs 824 825 # Fast path: no submessages, so the lists are already parallel. 826 if n_sec3 == n_msgs: 827 return list(range(n_msgs)) 828 829 offsets = index.get("sectionOffset") 830 if offsets is None: 831 # Nothing to map through; clamp so a malformed index degrades to the 832 # last known grid definition rather than raising IndexError. 833 return [min(i, n_sec3 - 1) for i in range(n_msgs)] 834 835 seen: Dict[int, int] = {} 836 sec3_map: List[int] = [] 837 for i in range(n_msgs): 838 try: 839 off = int(offsets[i][3]) 840 except (IndexError, KeyError, TypeError, ValueError): 841 sec3_map.append(sec3_map[-1] if sec3_map else 0) 842 continue 843 if off not in seen: 844 seen[off] = min(len(seen), n_sec3 - 1) 845 sec3_map.append(seen[off]) 846 return sec3_map 847 848 849def _remote_scan_storage_options(file_path: str, storage_options: Dict[str, Any]) -> Dict[str, Any]: 850 """Build tuned fsspec options for remote metadata scans. 851 852 These defaults reduce accidental large-block downloads while scanning 853 message headers/indices across large remote GRIB2 objects. 854 """ 855 tuned = { 856 "default_fill_cache": False, 857 "default_cache_type": "none", 858 "default_block_size": 131072, 859 } 860 861 # Public S3 GRIB2 archives are common; default to anonymous access 862 # unless the caller explicitly requests credentialed access. 863 if urlparse(file_path).scheme in {"s3", "s3a"} and "anon" not in storage_options: 864 tuned["anon"] = True 865 866 tuned.update(storage_options) 867 return tuned 868 869 870def _value_matches(val: float, filter_val: Any) -> bool: 871 """Return True if *val* satisfies the scalar / list / slice *filter_val*.""" 872 if isinstance(filter_val, (list, tuple, set)): 873 return val in filter_val or val in {float(v) for v in filter_val} 874 if isinstance(filter_val, slice): 875 lo = float(filter_val.start) if filter_val.start is not None else float("-inf") 876 hi = float(filter_val.stop) if filter_val.stop is not None else float("inf") 877 return lo <= val <= hi 878 return val == filter_val or val == float(filter_val) 879 880 881# Mapping from GRIB2 Table 4.5 typeOfFirstFixedSurface to wgrib2 .idx level 882# string prefixes for single-valued surfaces (no numeric level component). 883_TOFS_FIXED_STRINGS: Dict[int, tuple] = { 884 1: ("surface", "ground or water surface"), 885 6: ("max wind",), 886 7: ("tropopause",), 887 8: ("top of atmosphere", "nominal top of atmosphere"), 888 10: ("entire atmosphere",), 889 101: ("mean sea level",), 890} 891 892 893def _idx_level_matches(level_str: str, tofs: Any, level_filter: Any) -> bool: 894 """Return True if the wgrib2 ``.idx`` level string is consistent with filters. 895 896 Conservative: returns True when the level type is unrecognised so that 897 false negatives (silently skipping a matching message) are avoided. 898 899 Recognised mappings: 900 901 * ``typeOfFirstFixedSurface=103`` (height above ground, m): 902 ``"2 m above ground"`` 903 * ``typeOfFirstFixedSurface=100`` (isobaric surface, Pa): 904 ``"500 mb"`` — grib2io returns Pa so ``500 mb`` → ``level=50000``. 905 Both hPa and Pa values are tried to handle version differences. 906 * Fixed-label surfaces (1, 6, 7, 10, 11, 101): matched by keyword. 907 """ 908 if tofs is None and level_filter is None: 909 return True 910 911 # Height above ground in metres (tofs = 103) 912 if tofs == 103: 913 m = re.match(r"^(\d+(?:\.\d+)?)\s+m\s+above\s+ground", level_str) 914 if not m: 915 return False 916 return level_filter is None or _value_matches(float(m.group(1)), level_filter) 917 918 # Isobaric surface in Pa (tofs = 100); wgrib2 uses hPa ("mb") 919 if tofs == 100: 920 m = re.match(r"^(\d+(?:\.\d+)?)\s+mb", level_str) 921 if not m: 922 return False 923 if level_filter is None: 924 return True 925 idx_mb = float(m.group(1)) 926 # grib2io returns Pa (500 mb → 50000); accept both Pa and hPa 927 return _value_matches(idx_mb * 100, level_filter) or _value_matches(idx_mb, level_filter) 928 929 # Fixed-label surfaces with no numeric level component 930 if tofs in _TOFS_FIXED_STRINGS: 931 ls = level_str.lower() 932 return any(ls.startswith(s) for s in _TOFS_FIXED_STRINGS[tofs]) 933 934 # Unknown surface type — keep conservatively 935 return True 936 937 938def _prefilter_idx_offsets( 939 filehandle, 940 shortname: Optional[Union[str, Set[str]]] = None, 941 filters: Optional[Dict[str, Any]] = None, 942) -> List[int]: 943 """Parse a wgrib2 ``.idx`` sidecar and return byte offsets matching filters. 944 945 The wgrib2 ``.idx`` line format is:: 946 947 MSG_NUM:BYTE_OFFSET:d=YYYYMMDDCC:SHORTNAME:LEVEL:FORECAST: 948 949 *shortname* may be a single string, a set/list of strings, or ``None``. 950 When ``None`` the shortName is not constrained and every message is kept 951 unless another filter rules it out. When *filters* is provided, the level 952 string (``parts[4]``) is also checked against ``typeOfFirstFixedSurface`` 953 and ``level`` entries in *filters*, which can drastically reduce the number 954 of messages passed to :func:`build_index` (e.g. from ~50 TMP pressure 955 levels to 1 for T2M). 956 957 Returns an empty list if the sidecar cannot be parsed or contains no 958 matching messages. 959 """ 960 names: Optional[Set[str]] = None 961 if shortname is not None: 962 names = {shortname} if isinstance(shortname, str) else set(shortname) 963 tofs = filters.get("typeOfFirstFixedSurface") if filters else None 964 level_filter = filters.get("level") if filters else None 965 offsets: List[int] = [] 966 for line in filehandle: 967 if isinstance(line, bytes): 968 line = line.decode("utf-8", errors="replace") 969 parts = line.split(":") 970 if len(parts) >= 5 and (names is None or parts[3] in names): 971 # Level-string pre-filter: skip if we can definitively rule out a 972 # match from the .idx level description (e.g. "500 mb" vs "2 m 973 # above ground"). Conservative: unknown formats are kept. 974 if not _idx_level_matches(parts[4], tofs, level_filter): 975 continue 976 try: 977 offsets.append(int(parts[1])) 978 except ValueError: 979 continue 980 return offsets 981 982 983def _build_chunk_key(var_name: str, dim_indices: List[int]) -> str: 984 """Construct a Zarr chunk key like ``"TMP/0.0.0"``. 985 986 Parameters 987 ---------- 988 var_name : str 989 Variable name (top-level Zarr array name). 990 dim_indices : list of int 991 Integer indices along each non-spatial dimension. 992 993 Returns 994 ------- 995 str 996 Zarr chunk key, e.g. ``"TMP/0.1.0.0"`` where the trailing 997 two zeros are for the y and x spatial dimensions (always 0 998 since each message is one full grid). 999 """ 1000 parts = [str(i) for i in dim_indices] + ["0", "0"] 1001 return f"{var_name}/{'.'.join(parts)}" 1002 1003 1004def _build_zarray_metadata( 1005 msg, 1006 shape: List[int], 1007 chunks: List[int], 1008 codec_config: dict, 1009) -> dict: 1010 """Build ``.zarray`` JSON metadata for a variable. 1011 1012 Parameters 1013 ---------- 1014 msg : Grib2Message 1015 Representative message for dtype info. 1016 shape : list of int 1017 Full array shape including spatial dims. 1018 chunks : list of int 1019 Chunk shape (one message per chunk). 1020 codec_config : dict 1021 ``Grib2Codec`` configuration dict. 1022 1023 Returns 1024 ------- 1025 dict 1026 Zarr ``.zarray`` metadata. 1027 """ 1028 dtype = "<f4" if msg.typeOfValues == 0 else "<i4" 1029 1030 # Place the codec config in `filters` (a list) rather than `compressor` 1031 # (a single dict). VirtualiZarr v2's translator iterates the `compressor` 1032 # field directly, which unpacks a dict's keys instead of the dict itself. 1033 # Using `filters: [codec_config]` with `compressor: null` is handled 1034 # correctly by both VirtualiZarr and zarr v2/numcodecs via fsspec. 1035 return { 1036 "zarr_format": 2, 1037 "shape": shape, 1038 "chunks": chunks, 1039 "dtype": dtype, 1040 "fill_value": "NaN" if dtype == "<f4" else 0, 1041 "order": "C", 1042 "compressor": None, 1043 "filters": [codec_config], 1044 } 1045 1046 1047def _decode(md: Any) -> Optional[str]: 1048 """Return the plain-language definition of a ``Grib2Metadata`` value. 1049 1050 grib2io stores coded metadata as :class:`grib2io.templates.Grib2Metadata` 1051 objects whose ``definition`` attribute is the decoded string. Some code 1052 tables (e.g. Table 4.5) return a ``[definition, units]`` list; in that case 1053 only the description is taken. Returns ``None`` when no definition exists. 1054 """ 1055 if md is None: 1056 return None 1057 d = getattr(md, "definition", md) 1058 if isinstance(d, (list, tuple)): 1059 d = d[0] if d else None 1060 if d is None: 1061 return None 1062 return str(d) 1063 1064 1065def _cf_standard_name(msg) -> str: 1066 """Return the CF standard name for a message, or ``"unknown"``. 1067 1068 Mirrors the lookup used by grib2io's xarray backend so that manifests and 1069 the native backend agree on the CF vocabulary. 1070 """ 1071 record = grib2io.tables.get_table("shortname_to_cf").get(str(msg.shortName)) 1072 if record is None: 1073 return "unknown" 1074 return record.get("cf_standard_name") or "unknown" 1075 1076 1077def _cf_cell_methods(msg) -> Optional[str]: 1078 """Return the CF ``cell_methods`` string for a message, if any.""" 1079 record = grib2io.tables.get_table("shortname_to_cf").get(str(msg.shortName)) 1080 if record is None: 1081 return None 1082 return record.get("cf_cell_methods") 1083 1084 1085def _level_string(msg) -> str: 1086 """Return the human-readable wgrib2-style level/layer description. 1087 1088 Uses grib2io's ``Level`` descriptor (e.g. ``"500 mb"``, 1089 ``"2 m above ground"``), which is far more usable than the raw 1090 ``typeOfFirstFixedSurface`` code and ``valueOfFirstFixedSurface``. 1091 """ 1092 try: 1093 return str(msg.level) 1094 except Exception: 1095 return "" 1096 1097 1098def _timedelta_hours(td: Any) -> Optional[float]: 1099 """Convert a ``timedelta``-like value to hours, or ``None``. 1100 1101 Returns a plain ``float`` (whole hours collapse to e.g. ``24.0``) suitable 1102 for JSON serialization; returns ``None`` when the value is missing or not a 1103 duration. 1104 """ 1105 if td is None: 1106 return None 1107 total = getattr(td, "total_seconds", None) 1108 if total is None: 1109 return None 1110 return total() / 3600.0 1111 1112 1113# GRIB2 Code Table 4.9 (type of probability) -> the word used for it in 1114# variable names and which threshold limit(s) that type uses. 1115_PROBABILITY_NAMING: Dict[int, tuple] = { 1116 0: ("below", ("lower",)), 1117 1: ("above", ("upper",)), 1118 2: ("between", ("lower", "upper")), 1119 3: ("above", ("lower",)), 1120 4: ("below", ("upper",)), 1121 5: ("equal", ("lower",)), 1122 6: ("above_normal", ()), 1123 7: ("near_normal", ()), 1124 8: ("below_normal", ()), 1125} 1126 1127 1128def _probability_key(msg) -> Optional[tuple]: 1129 """Return ``(typeOfProbability, lower, upper)`` for a probability product. 1130 1131 Returns ``None`` for messages that are not probability products (only 1132 PDTs 4.5 and 4.9 carry these fields). A limit is ``None`` when the 1133 probability type does not use it: grib2io decodes a missing limit as 1134 ``0.0``, which must not leak into variable names or attributes. 1135 """ 1136 type_of_probability = getattr(msg, "typeOfProbability", None) 1137 if type_of_probability is None: 1138 return None 1139 type_of_probability = int(getattr(type_of_probability, "value", type_of_probability)) 1140 _, used = _PROBABILITY_NAMING.get(type_of_probability, (None, ("lower", "upper"))) 1141 lower = float(msg.thresholdLowerLimit) if "lower" in used else None 1142 upper = float(msg.thresholdUpperLimit) if "upper" in used else None 1143 return (type_of_probability, lower, upper) 1144 1145 1146def _format_threshold(value: float) -> str: 1147 """Format a threshold value for use in a variable name. 1148 1149 ``.`` and ``-`` are not safe in variable names, so the decimal point is 1150 written as ``p`` and a minus sign as ``m`` (the convention Panoply uses): 1151 ``304.8 -> "304p8"``, ``0.254 -> "0p254"``, ``-2.5 -> "m2p5"``. Whole 1152 numbers keep one decimal place (``50.0 -> "50p0"``). 1153 """ 1154 if value == 0: 1155 value = 0.0 # normalise -0.0 1156 text = f"{value:.6f}".rstrip("0") 1157 if text.endswith("."): 1158 text += "0" 1159 return text.replace("-", "m").replace(".", "p") 1160 1161 1162def _probability_suffix(prob_key: tuple) -> str: 1163 """Build the variable-name suffix for a probability product. 1164 1165 Examples: ``prob_between_1p0_and_2p0``, ``prob_below_304p8``, 1166 ``prob_above_0p254``, ``prob_above_normal``. 1167 """ 1168 type_of_probability, lower, upper = prob_key 1169 word, _ = _PROBABILITY_NAMING.get(type_of_probability, (f"type{type_of_probability}", ())) 1170 limits = [_format_threshold(v) for v in (lower, upper) if v is not None] 1171 if word == "between" and len(limits) == 2: 1172 return f"prob_between_{limits[0]}_and_{limits[1]}" 1173 return "_".join(["prob", word] + limits) 1174 1175 1176def _build_root_zattrs(msg) -> dict: 1177 """Build root-level (dataset) Zarr attributes from a representative message. 1178 1179 Combines CF global attributes with GRIB2 identification metadata decoded 1180 from Sections 0/1/4. This makes a manifest self-describing: which center 1181 produced it, from what model, for which reference cycle, and under what 1182 table versions — none of which the per-variable attributes capture. 1183 1184 Parameters 1185 ---------- 1186 msg : Grib2Message 1187 Representative message (all messages in a manifest are assumed to share 1188 the same originating center, model, and reference time). 1189 1190 Returns 1191 ------- 1192 dict 1193 Root ``.zattrs`` metadata. 1194 """ 1195 # Institution: originating center, with sub-center appended when defined. 1196 institution = _decode(getattr(msg, "originatingCenter", None)) 1197 subcenter = _decode(getattr(msg, "originatingSubCenter", None)) 1198 if institution and subcenter: 1199 institution = f"{institution} / {subcenter}" 1200 1201 # Reference time (model cycle) as ISO 8601. 1202 ref = getattr(msg, "refDate", None) 1203 if hasattr(ref, "isoformat"): 1204 reference_time = ref.isoformat() 1205 elif ref is not None: 1206 reference_time = str(ref) 1207 else: 1208 reference_time = None 1209 1210 zattrs: Dict[str, Any] = {"Conventions": "CF-1.8"} 1211 1212 # Only emit keys we could actually decode, so consumers never see 1213 # placeholder/None values in the manifest. 1214 for key, value in [ 1215 ("institution", institution), 1216 ("source", _decode(getattr(msg, "generatingProcess", None))), 1217 ("reference_time", reference_time), 1218 ("reference_time_significance", _decode(getattr(msg, "significanceOfReferenceTime", None))), 1219 ("production_status", _decode(getattr(msg, "productionStatus", None))), 1220 ("type_of_data", _decode(getattr(msg, "typeOfData", None))), 1221 ]: 1222 if value is not None: 1223 zattrs[key] = value 1224 1225 # GRIB2 table versions (numeric codes) for full reproducibility. 1226 master = getattr(msg, "masterTableInfo", None) 1227 if master is not None: 1228 zattrs["GRIB2_master_table_version"] = int(getattr(master, "value", master)) 1229 local = getattr(msg, "localTableInfo", None) 1230 if local is not None: 1231 zattrs["GRIB2_local_table_version"] = int(getattr(local, "value", local)) 1232 1233 version = getattr(grib2io, "__version__", None) 1234 if version: 1235 zattrs["grib2io_version"] = str(version) 1236 1237 return zattrs 1238 1239 1240def _build_zattrs(msg, dim_labels: List[str]) -> dict: 1241 """Extract GRIB2 section metadata as Zarr attributes. 1242 1243 Parameters 1244 ---------- 1245 msg : Grib2Message 1246 Representative message. 1247 dim_labels : list of str 1248 Ordered dimension names including ``"y"`` and ``"x"``. 1249 1250 Returns 1251 ------- 1252 dict 1253 Zarr ``.zattrs`` metadata. 1254 1255 Notes 1256 ----- 1257 ``level`` and ``valueOfFirstFixedSurface`` describe the representative 1258 message. They are meaningful only when the variable holds a single level; 1259 :meth:`ReferenceGenerator._build_variable_refs` removes them for variables 1260 that span a level dimension, where the level coordinate carries the values 1261 instead. 1262 """ 1263 # Extract typeOfFirstFixedSurface - handle Grib2Metadata objects 1264 type_of_first_fixed_surface = msg.typeOfFirstFixedSurface 1265 if hasattr(type_of_first_fixed_surface, "value"): 1266 type_of_first_fixed_surface = type_of_first_fixed_surface.value 1267 1268 # Extract valueOfFirstFixedSurface 1269 value_of_first_fixed_surface = msg.valueOfFirstFixedSurface 1270 if hasattr(value_of_first_fixed_surface, "value"): 1271 value_of_first_fixed_surface = value_of_first_fixed_surface.value 1272 1273 # Extract valid_time (= refDate + leadTime = msg.validDate) 1274 vt = getattr(msg, "validDate", None) 1275 if vt is None: 1276 try: 1277 vt = msg.refDate + msg.leadTime 1278 except Exception: 1279 vt = msg.refDate 1280 if hasattr(vt, "isoformat"): 1281 valid_time_str = vt.isoformat() 1282 elif isinstance(vt, np.datetime64): 1283 valid_time_str = str(vt) 1284 else: 1285 valid_time_str = str(vt) 1286 1287 zattrs = { 1288 "_ARRAY_DIMENSIONS": dim_labels, 1289 "coordinates": "latitude longitude", 1290 # CF vocabulary (Interoperable) ----------------------------------- 1291 "standard_name": _cf_standard_name(msg), 1292 "long_name": str(msg.fullName), 1293 "fullName": str(msg.fullName), 1294 "units": str(msg.units), 1295 # GRIB2-native provenance (kept alongside CF for Reusability) ----- 1296 "discipline": int(msg.section0[2]), 1297 "parameterCategory": int(msg.parameterCategory), 1298 "parameterNumber": int(msg.parameterNumber), 1299 "typeOfFirstFixedSurface": int(type_of_first_fixed_surface), 1300 "valueOfFirstFixedSurface": float(value_of_first_fixed_surface), 1301 "level": _level_string(msg), 1302 "shortName": str(msg.shortName), 1303 "valid_time": valid_time_str, 1304 } 1305 1306 # Representative forecast lead time. Distinguishes an f000 manifest from 1307 # an f384 one, which is otherwise only recoverable from the filename. 1308 lead_hours = _timedelta_hours(getattr(msg, "leadTime", None)) 1309 if lead_hours is not None: 1310 zattrs["lead_time_hours"] = lead_hours 1311 1312 # Statistical processing period (e.g. accumulation/max/min window); only 1313 # meaningful for messages that carry one. 1314 dur_hours = _timedelta_hours(getattr(msg, "duration", None)) 1315 if dur_hours: 1316 zattrs["duration_hours"] = dur_hours 1317 1318 # CF cell_methods only when the parameter defines one (e.g. time: maximum). 1319 cell_methods = _cf_cell_methods(msg) 1320 if cell_methods: 1321 zattrs["cell_methods"] = cell_methods 1322 1323 # Probability products: record the threshold the variable name was derived 1324 # from, so the distinction is machine-readable and not only in the name. 1325 prob_key = _probability_key(msg) 1326 if prob_key is not None: 1327 type_of_probability, lower, upper = prob_key 1328 zattrs["typeOfProbability"] = type_of_probability 1329 if lower is not None: 1330 zattrs["thresholdLowerLimit"] = lower 1331 if upper is not None: 1332 zattrs["thresholdUpperLimit"] = upper 1333 1334 return zattrs 1335 1336 1337def _build_codec_config(entry: _MsgEntry) -> dict: 1338 """Build ``Grib2Codec`` configuration from a message entry. 1339 1340 Parameters 1341 ---------- 1342 entry : _MsgEntry 1343 Scanned message entry with index metadata. 1344 1345 Returns 1346 ------- 1347 dict 1348 Codec configuration suitable for ``Grib2Codec.from_config()``. 1349 """ 1350 msg = entry.msg 1351 sec3 = entry.index_section3 1352 sec5 = entry.index_section5 1353 1354 # GDS: first 5 elements of section 3 1355 gds = [int(x) for x in sec3[:5]] 1356 # GDT: remaining elements of section 3 1357 gdt = [int(x) for x in sec3[5:]] 1358 # DRT number and template 1359 drtn = int(sec5[1]) 1360 drt = [int(x) for x in sec5[2:]] 1361 1362 # Grid dimensions 1363 nx = int(msg.nx) 1364 ny = int(msg.ny) 1365 1366 # Scan mode flags 1367 scan_mode_flags = None 1368 if hasattr(msg, "scanModeFlags"): 1369 scan_mode_flags = [int(x) for x in msg.scanModeFlags] 1370 1371 # Bitmap info 1372 bitmap_flag = int(entry.bmapflag) 1373 bitmap_offset = None 1374 bitmap_length = None 1375 if bitmap_flag in {0, 254} and entry.sec6_offset is not None: 1376 bitmap_offset = int(entry.sec6_offset) 1377 bitmap_length = int(entry.sec6_length) 1378 1379 # Number of data points and packed values 1380 number_of_data_points = int(msg.numberOfDataPoints) 1381 number_of_packed_values = int(msg.numberOfPackedValues) 1382 1383 # Type of values 1384 type_of_values = int(msg.typeOfValues) if hasattr(msg, "typeOfValues") else 0 1385 1386 # Emit a Zarr v2/v3-compatible codec config dict for VirtualiZarr compatibility. 1387 config = { 1388 "id": "grib2io", 1389 "drtn": drtn, 1390 "drt": drt, 1391 "gdtn": int(msg.gdtn), 1392 "gdt": gdt, 1393 "gds": gds, 1394 "nx": nx, 1395 "ny": ny, 1396 "bitmap_flag": bitmap_flag, 1397 "bitmap_offset": bitmap_offset, 1398 "bitmap_length": bitmap_length, 1399 "scan_mode_flags": scan_mode_flags, 1400 "type_of_values": type_of_values, 1401 "number_of_data_points": number_of_data_points, 1402 "number_of_packed_values": number_of_packed_values, 1403 } 1404 # For VirtualiZarr, the 'compressor' field must be a dict, not a string or id. 1405 return config 1406 1407 1408def _get_dim_value(msg, dim_name: str) -> Any: 1409 """Extract a dimension coordinate value from a message. 1410 1411 Parameters 1412 ---------- 1413 msg : Grib2Message 1414 The GRIB2 message. 1415 dim_name : str 1416 Dimension name. 1417 1418 Returns 1419 ------- 1420 Any 1421 The coordinate value, converted to a hashable/sortable type. 1422 """ 1423 if dim_name == "level": 1424 # Use the tuple (valueOfFirstFixedSurface, valueOfSecondFixedSurface) 1425 # as the level identifier, matching xarray_backend logic 1426 v1 = msg.valueOfFirstFixedSurface 1427 v2 = msg.valueOfSecondFixedSurface 1428 return (float(v1), float(v2)) 1429 elif dim_name == "valid_time": 1430 # valid_time = refDate + leadTime (i.e. msg.validDate) 1431 vt = getattr(msg, "validDate", None) 1432 if vt is None: 1433 rd = msg.refDate 1434 lt = msg.leadTime 1435 try: 1436 vt = rd + lt 1437 except Exception: 1438 vt = rd 1439 if hasattr(vt, "isoformat"): 1440 return vt.isoformat() 1441 if isinstance(vt, np.datetime64): 1442 return str(vt) 1443 return str(vt) 1444 elif dim_name == "duration": 1445 d = msg.duration 1446 if hasattr(d, "total_seconds"): 1447 return d.total_seconds() 1448 return str(d) 1449 else: 1450 val = getattr(msg, dim_name, None) 1451 if hasattr(val, "value"): 1452 val = val.value 1453 return val 1454 1455 1456def _map_messages_to_dimensions( 1457 msg_entries: List[_MsgEntry], 1458 level_dim_name: str = "level", 1459) -> dict: 1460 """Group messages by variable and map to dimension indices. 1461 1462 This mirrors the logic in ``parse_grib_index()`` from the xarray 1463 backend: for each message, extract the values of potential dimension 1464 coordinates (level, leadTime, refDate, perturbationNumber, etc.), 1465 determine which dimensions have more than one unique value, and 1466 build a mapping from dimension-value tuples to message indices. 1467 1468 Parameters 1469 ---------- 1470 msg_entries : list of _MsgEntry 1471 All message entries for a single variable. 1472 1473 Returns 1474 ------- 1475 dict 1476 Dictionary with keys: 1477 - ``"dim_names"``: ordered list of active dimension names 1478 - ``"dim_values"``: dict mapping dim name to sorted unique values 1479 - ``"msg_index_map"``: dict mapping dim-value tuple to entry index 1480 - ``"duplicate_entry_indices"``: indices of entries whose dim-value 1481 tuple exactly collided with an earlier entry's 1482 """ 1483 # Build ordered dim names, substituting the surface-type-specific level name 1484 ordered_dims = [level_dim_name if d == "level" else d for d in _ORDERED_DIM_NAMES] 1485 1486 # Collect dimension values for each message 1487 all_dim_vals: Dict[str, list] = {d: [] for d in ordered_dims} 1488 1489 for entry in msg_entries: 1490 msg = entry.msg 1491 for dim_name in ordered_dims: 1492 # Map the (possibly renamed) level dim back to "level" for _get_dim_value 1493 orig_name = "level" if dim_name == level_dim_name else dim_name 1494 try: 1495 val = _get_dim_value(msg, orig_name) 1496 all_dim_vals[dim_name].append(val) 1497 except (AttributeError, TypeError): 1498 all_dim_vals[dim_name].append(None) 1499 1500 # Determine which dimensions are active (have >1 unique value) 1501 active_dims = [] 1502 dim_values: Dict[str, list] = {} 1503 1504 for dim_name in ordered_dims: 1505 vals = all_dim_vals[dim_name] 1506 # Filter out None values 1507 non_none = [v for v in vals if v is not None] 1508 if not non_none: 1509 continue 1510 unique_vals = sorted(set(non_none)) 1511 if len(unique_vals) > 1: 1512 active_dims.append(dim_name) 1513 dim_values[dim_name] = unique_vals 1514 elif len(unique_vals) == 1: 1515 # Always emit valid_time and the level dim (so multi-file concat 1516 # can grow those axes). All other dims are optional: only emit 1517 # them when they actually vary within this variable group. 1518 if dim_name in _ALWAYS_INCLUDE_DIMS or dim_name == level_dim_name: 1519 active_dims.append(dim_name) 1520 dim_values[dim_name] = unique_vals 1521 1522 # If no dimensions are active at all, fall back to a single valid_time 1523 if not active_dims: 1524 msg = msg_entries[0].msg 1525 vt = _get_dim_value(msg, "valid_time") 1526 active_dims = ["valid_time"] 1527 dim_values = {"valid_time": [vt]} 1528 1529 # Remap back so callers can use dim_names as coordinate keys directly 1530 # (level_dim_name is already baked in via ordered_dims) 1531 1532 # Build the mapping from dimension-value tuples to entry indices. 1533 # Two messages can carry fully identical identifying metadata (same 1534 # parameter, level, lead time, PDT) yet contain different data -- 1535 # smartinit encodes a 1-bit binary field with the same IDs as the real 1536 # surface TMP. Overwriting would silently drop the earlier message's 1537 # bytes from the manifest, so collisions are collected for the caller 1538 # to emit as a separate variable instead. 1539 msg_index_map: Dict[tuple, int] = {} 1540 duplicate_entry_indices: List[int] = [] 1541 for idx, entry in enumerate(msg_entries): 1542 msg = entry.msg 1543 dim_tuple = tuple(_get_dim_value(msg, "level" if d == level_dim_name else d) for d in active_dims) 1544 if dim_tuple in msg_index_map: 1545 duplicate_entry_indices.append(idx) 1546 else: 1547 msg_index_map[dim_tuple] = idx 1548 1549 return { 1550 "dim_names": active_dims, 1551 "dim_values": dim_values, 1552 "msg_index_map": msg_index_map, 1553 "duplicate_entry_indices": duplicate_entry_indices, 1554 } 1555 1556 1557# CF attributes for vertical coordinates, keyed by GRIB2 Table 4.5 1558# typeOfFirstFixedSurface. Values are ``(standard_name, positive)``; either 1559# element may be ``None`` when CF does not define it. Units are read from 1560# Table 4.5 itself rather than duplicated here. 1561# 1562# Single-valued surfaces (mean sea level, tropopause, planetary boundary layer, 1563# entire atmosphere) are deliberately absent: they are labels rather than 1564# measurable vertical coordinates, and the CF standard names that sound 1565# applicable — air_pressure_at_mean_sea_level, for instance — belong to the data 1566# variable, not to the coordinate it sits on. Those surfaces still receive 1567# units and a long_name from Table 4.5. 1568_CF_LEVEL_ATTRS: Dict[int, tuple] = { 1569 100: ("air_pressure", "down"), # isobaric surface 1570 102: ("altitude", "up"), # specific altitude above mean sea level 1571 103: ("height", "up"), # specified height above ground 1572 # CF's atmosphere_sigma_coordinate and 1573 # atmosphere_hybrid_sigma_pressure_coordinate are parametric and require 1574 # formula_terms referencing the surface-pressure and coefficient variables. 1575 # Those are not present in a kerchunk manifest, so claiming the 1576 # standard_name without them would be non-conformant. Direction alone is 1577 # both safe and useful. 1578 104: (None, "down"), # sigma level 1579 105: (None, "down"), # hybrid level 1580 106: ("depth", "down"), # depth below land surface 1581 107: ("air_potential_temperature", "up"), # isentropic (theta) level 1582 108: ("air_pressure", "down"), # pressure difference from ground 1583 109: ("ertel_potential_vorticity", "up"), # potential vorticity surface 1584 160: ("depth", "down"), # depth below sea level 1585} 1586 1587 1588def _level_coord_attrs(msg, dim_name: str) -> dict: 1589 """Build CF attributes for a vertical coordinate variable. 1590 1591 A vertical coordinate carrying only ``_ARRAY_DIMENSIONS`` is not 1592 CF-conformant and leaves a consumer unable to distinguish Pa from hPa 1593 except by inspecting the magnitude of the values. Units and a description 1594 come from Table 4.5, which grib2io already loads; ``standard_name`` and 1595 ``positive`` come from :data:`_CF_LEVEL_ATTRS` where CF defines them. 1596 1597 Parameters 1598 ---------- 1599 msg : Grib2Message 1600 Representative message for the variable using this coordinate. 1601 dim_name : str 1602 Coordinate name, used only as a ``long_name`` fallback. 1603 1604 Returns 1605 ------- 1606 dict 1607 Attributes to merge into the coordinate's ``.zattrs``. Empty when the 1608 surface type cannot be determined. 1609 """ 1610 toffs = getattr(msg, "typeOfFirstFixedSurface", None) 1611 if toffs is None: 1612 return {} 1613 val = getattr(toffs, "value", toffs) 1614 try: 1615 val = int(val) 1616 except (TypeError, ValueError): 1617 return {} 1618 1619 attrs: Dict[str, Any] = {} 1620 1621 # Units and a human-readable description from Table 4.5, whose entries are 1622 # ``[definition, units]``. "unknown" units are omitted rather than emitted 1623 # literally, since an explicit "unknown" is worse than a missing attribute. 1624 try: 1625 entry = grib2io.tables.get_table("4.5").get(str(val)) 1626 except Exception: 1627 entry = None 1628 if entry: 1629 description = str(entry[0]) if len(entry) > 0 else "" 1630 units = str(entry[1]) if len(entry) > 1 else "" 1631 if units and units.lower() != "unknown": 1632 attrs["units"] = units 1633 if description: 1634 attrs["long_name"] = description 1635 1636 if "long_name" not in attrs: 1637 attrs["long_name"] = dim_name.replace("_", " ") 1638 1639 cf = _CF_LEVEL_ATTRS.get(val) 1640 if cf: 1641 standard_name, positive = cf 1642 if standard_name: 1643 attrs["standard_name"] = standard_name 1644 if positive: 1645 attrs["positive"] = positive 1646 1647 # Retain the GRIB2-native surface code alongside the CF vocabulary, for the 1648 # same reason the data variables keep theirs. 1649 attrs["typeOfFirstFixedSurface"] = val 1650 return attrs 1651 1652 1653def _resolve_dim_names( 1654 dim_names: List[str], 1655 dim_values: Dict[str, list], 1656 registry: Optional[Dict[str, list]], 1657) -> Dict[str, str]: 1658 """Map each dimension to the name it should be emitted under. 1659 1660 A kerchunk manifest is a single flat Zarr group, so a dimension name means 1661 one thing across the whole file. Variables within a GRIB2 file frequently 1662 disagree about a dimension's extent -- different pressure-level sets, some 1663 fields at 7 percentiles and others at 3, accumulations over different 1664 windows -- and whichever variable is written last would otherwise overwrite 1665 the coordinate array, leaving earlier variables pointing at a coordinate of 1666 the wrong length. xarray then refuses to open the dataset. 1667 1668 Any dimension whose values differ from what the registry already holds is 1669 given a numeric suffix ('percentileValue_2'), matching how the xarray 1670 backend keeps each surface type in its own Dataset. Dimensions whose 1671 values match an existing entry share it, so unrelated variables at the same 1672 levels continue to use one coordinate. 1673 1674 Parameters 1675 ---------- 1676 dim_names : list of str 1677 Base dimension names for this variable, in order. 1678 dim_values : dict 1679 Base dimension name -> sorted unique coordinate values. 1680 registry : dict or None 1681 Emitted name -> values already written to the manifest. Updated in 1682 place. When ``None``, names pass through unchanged. 1683 1684 Returns 1685 ------- 1686 dict 1687 Base dimension name -> emitted dimension name. 1688 """ 1689 out: Dict[str, str] = {} 1690 for d in dim_names: 1691 if registry is None: 1692 out[d] = d 1693 continue 1694 vals = dim_values.get(d, []) 1695 name = d 1696 if name in registry and registry[name] != vals: 1697 suffix = 2 1698 candidate = f"{d}_{suffix}" 1699 while candidate in registry and registry[candidate] != vals: 1700 suffix += 1 1701 candidate = f"{d}_{suffix}" 1702 name = candidate 1703 if name not in registry: 1704 registry[name] = vals 1705 out[d] = name 1706 return out 1707 1708 1709def _build_coord_refs( 1710 dim_name: str, 1711 values: list, 1712 refs: Dict[str, Any], 1713 msg=None, 1714 is_level: bool = False, 1715 base_name: Optional[str] = None, 1716) -> None: 1717 """Build inline base64-encoded coordinate array refs. 1718 1719 Parameters 1720 ---------- 1721 dim_name : str 1722 Name the coordinate is emitted under. May carry a numeric suffix 1723 assigned by :func:`_resolve_dim_names`. 1724 values : list 1725 Sorted unique coordinate values. 1726 refs : dict 1727 The refs dict to populate. 1728 msg : Grib2Message, optional 1729 Representative message, used to derive CF attributes for the vertical 1730 coordinate. When omitted the coordinate is written without them. 1731 is_level : bool, default False 1732 Whether this is the variable's vertical dimension. Only that 1733 coordinate receives vertical-coordinate attributes. 1734 base_name : str, optional 1735 Unsuffixed dimension name. Value encoding and the time/duration 1736 attributes are chosen from this, so that a renamed dimension such as 1737 ``valid_time_2`` is still encoded as datetime64 rather than falling 1738 through to the float64 default. Defaults to *dim_name*. 1739 """ 1740 base = base_name or dim_name 1741 if values and isinstance(values[0], tuple): 1742 # Level-type coordinate: values are (v1, v2) tuples; use v1 1743 coord_values = np.array( 1744 [v[0] if isinstance(v, tuple) else float(v) for v in values], 1745 dtype=np.float64, 1746 ) 1747 elif base == "valid_time": 1748 # Store as int64 nanoseconds since epoch so xarray decodes as datetime64 1749 ns_vals = [int(np.datetime64(v, "ns").astype(np.int64)) for v in values] 1750 coord_values = np.array(ns_vals, dtype=np.int64) 1751 elif base == "duration": 1752 # Store as float seconds 1753 coord_values = np.array(values, dtype=np.float64) 1754 elif base == "perturbationNumber": 1755 coord_values = np.array(values, dtype=np.int32) 1756 elif base == "percentileValue": 1757 coord_values = np.array(values, dtype=np.float64) 1758 else: 1759 coord_values = np.array(values, dtype=np.float64) 1760 1761 # Encode as base64 1762 raw_bytes = coord_values.tobytes() 1763 b64_data = base64.b64encode(raw_bytes).decode("ascii") 1764 1765 # .zarray for the coordinate 1766 coord_zarray = { 1767 "zarr_format": 2, 1768 "shape": [len(values)], 1769 "chunks": [len(values)], 1770 "dtype": coord_values.dtype.str, 1771 "fill_value": None if coord_values.dtype.kind in {"U", "S"} else 0, 1772 "order": "C", 1773 "compressor": None, 1774 "filters": None, 1775 } 1776 refs[f"{dim_name}/.zarray"] = json.dumps(coord_zarray) 1777 1778 # .zattrs for the coordinate 1779 coord_zattrs: Dict[str, Any] = {"_ARRAY_DIMENSIONS": [dim_name]} 1780 if base == "valid_time": 1781 # CF-compliant time metadata so xarray decodes int64 ns as datetime64 1782 coord_zattrs["units"] = "nanoseconds since 1970-01-01T00:00:00" 1783 coord_zattrs["calendar"] = "proleptic_gregorian" 1784 elif base == "duration": 1785 coord_zattrs["units"] = "seconds" 1786 coord_zattrs["long_name"] = "time period over which the field applies" 1787 elif base == "percentileValue": 1788 coord_zattrs["units"] = "%" 1789 coord_zattrs["long_name"] = "percentile" 1790 elif base == "perturbationNumber": 1791 coord_zattrs["long_name"] = "ensemble member number" 1792 elif msg is not None and is_level: 1793 # Vertical coordinate: CF requires units here, and the level 1794 # description belongs on the coordinate rather than repeated (and 1795 # wrong) on every data variable that uses it. 1796 coord_zattrs.update(_level_coord_attrs(msg, dim_name)) 1797 1798 # Several variables can share a level dimension, and this function is 1799 # called once per variable. Keep whichever attribute set is richer so a 1800 # later, barer write does not strip metadata an earlier one supplied. 1801 existing = refs.get(f"{dim_name}/.zattrs") 1802 if existing is not None: 1803 try: 1804 prev = json.loads(existing) 1805 except (TypeError, ValueError): 1806 prev = {} 1807 if len(prev) > len(coord_zattrs): 1808 coord_zattrs = prev 1809 1810 refs[f"{dim_name}/.zattrs"] = json.dumps(coord_zattrs) 1811 1812 # Inline data chunk 1813 refs[f"{dim_name}/0"] = "base64:" + b64_data 1814 1815 1816def _validate_refs(refs: Dict[str, Any]) -> List[tuple]: 1817 """Check a finished manifest for internal consistency. 1818 1819 A kerchunk manifest is only useful if it can be opened. The failure mode 1820 worth catching here is a variable whose array shape disagrees with the 1821 length of a coordinate it names: the manifest serializes cleanly, uploads 1822 cleanly, and then fails at ``xr.open_dataset`` with a conflicting-sizes 1823 error that names the variables but not the cause. Catching it at 1824 generation time turns a downstream mystery into an immediate, local error. 1825 1826 Parameters 1827 ---------- 1828 refs : dict 1829 The finished ``refs`` mapping. 1830 1831 Returns 1832 ------- 1833 list of tuple 1834 ``(variable, dimension, variable_length, coordinate_length)`` for each 1835 mismatch found. Empty when the manifest is self-consistent. 1836 """ 1837 # Lengths of the 1-D coordinate arrays. latitude/longitude are 2-D and are 1838 # not dimensions, so they are skipped. 1839 coord_len: Dict[str, int] = {} 1840 for key, val in refs.items(): 1841 if not key.endswith("/.zarray") or key.count("/") != 1: 1842 continue 1843 try: 1844 shape = json.loads(val)["shape"] 1845 except (TypeError, ValueError, KeyError): 1846 continue 1847 if len(shape) == 1: 1848 coord_len[key.split("/")[0]] = int(shape[0]) 1849 1850 problems: List[tuple] = [] 1851 for key, val in refs.items(): 1852 if not key.endswith("/.zattrs") or key.count("/") != 1: 1853 continue 1854 name = key.split("/")[0] 1855 try: 1856 attrs = json.loads(val) 1857 except (TypeError, ValueError): 1858 continue 1859 if "shortName" not in attrs: 1860 continue # coordinate, not a data variable 1861 zarray_key = f"{name}/.zarray" 1862 if zarray_key not in refs: 1863 continue 1864 try: 1865 shape = json.loads(refs[zarray_key])["shape"] 1866 except (TypeError, ValueError, KeyError): 1867 continue 1868 for dim, length in zip(attrs.get("_ARRAY_DIMENSIONS", []), shape): 1869 if dim in coord_len and coord_len[dim] != int(length): 1870 problems.append((name, dim, int(length), coord_len[dim])) 1871 1872 return problems 1873 1874 1875def _format_validation_errors(problems: List[tuple], limit: int = 10) -> str: 1876 """Render :func:`_validate_refs` output as an actionable error message.""" 1877 dims = sorted({p[1] for p in problems}) 1878 lines = [ 1879 f"Manifest is internally inconsistent: {len(problems)} variable/dimension pairs disagree with their coordinate arrays.", 1880 f"Affected dimensions: {', '.join(dims)}", 1881 "", 1882 ] 1883 for var, dim, got, expected in problems[:limit]: 1884 lines.append(f" {var}: dimension '{dim}' has length {got}, but the coordinate array has length {expected}") 1885 if len(problems) > limit: 1886 lines.append(f" ... and {len(problems) - limit} more") 1887 lines += [ 1888 "", 1889 "This manifest would fail to open with xarray. It usually means two " 1890 "variables need different values for the same dimension and one " 1891 "overwrote the other's coordinate array; _resolve_dim_names should " 1892 "have given them distinct names.", 1893 "Pass validate=False to ReferenceGenerator to emit it anyway.", 1894 ] 1895 return "\n".join(lines) 1896 1897 1898def _build_latlon_coord_refs(msg, refs: Dict[str, Any]) -> None: 1899 """Build inline latitude/longitude 2-D coordinate arrays from the grid. 1900 1901 Calls ``msg.latlons()`` to compute the full (ny, nx) grids and encodes 1902 them as base64 inline Zarr refs, matching the xarray backend's behaviour. 1903 """ 1904 try: 1905 lats, lons = msg.latlons() 1906 except Exception: 1907 return 1908 1909 ny, nx = int(msg.ny), int(msg.nx) 1910 1911 for name, data, attrs in [ 1912 ( 1913 "latitude", 1914 lats.astype(np.float64), 1915 { 1916 "_ARRAY_DIMENSIONS": ["y", "x"], 1917 "standard_name": "latitude", 1918 "units": "degrees_north", 1919 }, 1920 ), 1921 ( 1922 "longitude", 1923 lons.astype(np.float64), 1924 { 1925 "_ARRAY_DIMENSIONS": ["y", "x"], 1926 "standard_name": "longitude", 1927 "units": "degrees_east", 1928 }, 1929 ), 1930 ]: 1931 # Skip if already present (e.g. from a prior variable group) 1932 if f"{name}/.zarray" in refs: 1933 continue 1934 1935 zarray = { 1936 "zarr_format": 2, 1937 "shape": [ny, nx], 1938 "chunks": [ny, nx], 1939 "dtype": "<f8", 1940 "fill_value": None, 1941 "order": "C", 1942 "compressor": None, 1943 "filters": None, 1944 } 1945 refs[f"{name}/.zarray"] = json.dumps(zarray) 1946 refs[f"{name}/.zattrs"] = json.dumps(attrs) 1947 refs[f"{name}/0.0"] = "base64:" + base64.b64encode(data.tobytes()).decode("ascii")
class
ReferenceGenerator:
117class ReferenceGenerator: 118 """Generate Kerchunk v1 reference manifests from GRIB2 files. 119 120 Parameters 121 ---------- 122 file_paths : str or list of str 123 One or more GRIB2 file paths (local paths or URIs). 124 filters : dict, optional 125 Filter GRIB2 messages by metadata attributes. Keys can be any 126 ``Grib2Message`` attribute name (e.g. ``shortName``, ``leadTime``). 127 storage_options : dict, optional 128 Extra options passed to ``fsspec.open`` for remote URIs 129 (e.g. ``{"anon": True}`` for public S3 buckets). 130 validate : bool, default True 131 Check the finished manifest for internal consistency before returning 132 it, and raise :class:`ValueError` if any variable's dimension lengths 133 disagree with the coordinate arrays it references. Pass ``False`` to 134 emit the manifest regardless. 135 """ 136 137 def __init__( 138 self, 139 file_paths: Union[str, List[str]], 140 filters: Optional[Dict[str, Any]] = None, 141 storage_options: Optional[Dict[str, Any]] = None, 142 max_workers: Optional[int] = None, 143 validate: bool = True, 144 ): 145 _ensure_numcodecs() 146 147 if isinstance(file_paths, (str, os.PathLike)): 148 file_paths = [str(file_paths)] 149 else: 150 file_paths = [str(p) for p in file_paths] 151 152 # Validate file accessibility. 153 # Local filesystem paths must exist. URI inputs are handled by 154 # grib2io.open/fsspec at scan time and should not be rejected here. 155 for fp in file_paths: 156 if _is_local_path(fp) and not os.path.isfile(fp): 157 raise FileNotFoundError(f"GRIB2 file not found: {fp}") 158 159 self.file_paths = file_paths 160 self.filters = filters or {} 161 self.storage_options = storage_options or {} 162 self.max_workers = max_workers 163 self.validate = validate 164 self._manifest: Optional[dict] = None 165 166 def generate(self) -> dict: 167 """Scan files and produce a Kerchunk v1 reference manifest. 168 169 Returns 170 ------- 171 dict 172 Kerchunk reference spec v1 dict with keys ``"version"`` and 173 ``"refs"``. 174 """ 175 refs: Dict[str, Any] = {} 176 177 # .zgroup at root 178 refs[".zgroup"] = json.dumps({"zarr_format": 2}) 179 180 # Collect all messages across files, keyed by variable group 181 # group_key = (shortName, typeOfFirstFixedSurface, pdtn, typeOfSecondFixedSurface, probability_key) 182 # This ensures messages with different surface types are not mixed. 183 all_var_messages: Dict[tuple, list] = {} 184 185 n_files = len(self.file_paths) 186 use_parallel = self.max_workers != 1 and n_files > 1 and not _is_local_path(self.file_paths[0]) 187 188 if use_parallel: 189 import concurrent.futures 190 191 workers = self.max_workers or min(n_files, 8) 192 193 def _scan_one(file_path): 194 file_uri = _file_uri(file_path) 195 local_msgs: Dict[tuple, list] = {} 196 self._scan_file(file_path, file_uri, local_msgs) 197 return local_msgs 198 199 with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: 200 futures = {pool.submit(_scan_one, fp): fp for fp in self.file_paths} 201 for future in concurrent.futures.as_completed(futures): 202 fp = futures[future] 203 try: 204 local_msgs = future.result() 205 for key, entries in local_msgs.items(): 206 all_var_messages.setdefault(key, []).extend(entries) 207 except Exception as e: 208 raise ValueError(f"Failed to parse GRIB2 file '{fp}': {e}") from e 209 else: 210 for file_path in self.file_paths: 211 file_uri = _file_uri(file_path) 212 try: 213 self._scan_file(file_path, file_uri, all_var_messages) 214 except Exception as e: 215 raise ValueError(f"Failed to parse GRIB2 file '{file_path}': {e}") from e 216 217 # For each variable group, map messages to dimensions and build refs. 218 # Track used variable names to handle collisions (same shortName 219 # but different surface types). 220 # Also track level coord name -> level values so that the same surface 221 # type but different level extents get disambiguated names (mirrors 222 # how the xarray backend keeps each surface type in its own Dataset). 223 used_var_names: Dict[str, int] = {} 224 # Emitted dimension name -> coordinate values written under it. Shared 225 # across every variable so that two variables needing different values 226 # for the same dimension get distinct names instead of one silently 227 # overwriting the other's coordinate array. 228 dim_coord_registry: Dict[str, list] = {} 229 for group_key, msg_entries in all_var_messages.items(): 230 var_name = group_key[0] # shortName is the first element 231 # Probability products are named for their threshold so each one 232 # is self-describing, e.g. PTYPE_prob_between_1p0_and_2p0. 233 prob_key = group_key[4] 234 if prob_key is not None: 235 var_name = f"{var_name}_{_probability_suffix(prob_key)}" 236 if var_name in used_var_names: 237 used_var_names[var_name] += 1 238 zarr_var_name = f"{var_name}_{used_var_names[var_name]}" 239 else: 240 used_var_names[var_name] = 0 241 zarr_var_name = var_name 242 self._build_variable_refs(zarr_var_name, msg_entries, refs, dim_coord_registry) 243 244 # Build latitude/longitude coordinate arrays from the grid definition. 245 # All messages are assumed to share the same grid (required by the 246 # xarray backend too), so we use the first available message. 247 if all_var_messages: 248 first_entries = next(iter(all_var_messages.values())) 249 rep_msg = first_entries[0].msg 250 _build_latlon_coord_refs(rep_msg, refs) 251 252 # Root-level dataset metadata (CF global attributes + GRIB2 253 # provenance from Sections 0/1/4). Without this, a manifest 254 # separated from its filename carries no record of which model, 255 # center, or cycle it describes. 256 refs[".zattrs"] = json.dumps(_build_root_zattrs(rep_msg)) 257 258 if self.validate: 259 problems = _validate_refs(refs) 260 if problems: 261 raise ValueError(_format_validation_errors(problems)) 262 263 self._manifest = {"version": 1, "refs": refs} 264 return self._manifest 265 266 def to_json(self, output_path: str) -> None: 267 """Serialize the manifest to a JSON file. 268 269 Parameters 270 ---------- 271 output_path : str 272 Path to the output JSON file. 273 """ 274 if self._manifest is None: 275 self.generate() 276 with open(output_path, "w") as f: 277 json.dump(self._manifest, f) 278 279 def to_parquet(self, output_path: str) -> None: 280 """Serialize the manifest to a Parquet reference store. 281 282 Parameters 283 ---------- 284 output_path : str 285 Path to the output Parquet directory. 286 """ 287 _ensure_kerchunk() 288 if self._manifest is None: 289 self.generate() 290 291 import fsspec 292 from fsspec.implementations.reference import LazyReferenceMapper 293 294 fs, _ = fsspec.core.url_to_fs(output_path) 295 out = LazyReferenceMapper.create(output_path, fs=fs, record_size=100_000, engine="pyarrow") 296 refs = self._manifest.get("refs", self._manifest) 297 for k in sorted(refs): 298 out[k] = refs[k] 299 out.flush() 300 301 # ------------------------------------------------------------------ 302 # Internal scanning 303 # ------------------------------------------------------------------ 304 305 def _build_remote_index_filtered( 306 self, 307 file_path: str, 308 shortname_filter: Optional[Union[str, Set[str]]] = None, 309 scan_storage_options: Optional[dict] = None, 310 ): 311 """Build a GRIB2 index for a remote file using sidecar pre-filtering. 312 313 Works with any combination of filters: a ``shortName`` alone, 314 ``shortName`` plus additional filters (e.g. ``typeOfFirstFixedSurface`` 315 / ``level``), or filters without a ``shortName`` at all. 316 317 Instead of fetching headers for every message (~700 HTTP requests for a 318 full GFS 0.25° file), this method: 319 320 1. Checks grib2io's local cache – if the full or filtered index was 321 saved from a previous run, it loads it instantly. 322 2. Checks for a remote grib2io ``.grib2ioidx`` sidecar (binary index) 323 alongside the GRIB2 file — the most efficient format, containing 324 pre-parsed section offsets and avoiding header reads entirely. 325 3. Fetches the wgrib2 ``.idx`` text sidecar and keeps only the byte 326 offsets whose shortName matches the filter, reducing HTTP range 327 requests from ~700 to ~1–50. 328 4. Saves the partial index to a filter-specific cache key so the next 329 call for the same file+filter is also instant. 330 5. Falls back to ``grib2io.open`` (full index, slow on first call) if 331 no sidecar is available. 332 333 Returns 334 ------- 335 tuple(dict, list) 336 ``(index, msgs)`` where *index* is a grib2io index dict and *msgs* 337 is a list of :class:`~grib2io.Grib2Message` objects. 338 """ 339 import builtins 340 import hashlib 341 import pickle 342 343 import fsspec 344 345 from grib2io._grib2io import build_index 346 from grib2io import msgs_from_index 347 348 scan_storage_options = scan_storage_options or {} 349 cache_root = os.path.join(os.path.expanduser("~"), ".cache", "grib2io") 350 351 # Open the remote file to obtain its size (one lightweight HEAD/info call). 352 # For the filtered fast-path we override cache settings: "readahead" with 353 # a small block size means consecutive section-header reads within the same 354 # message share one HTTP range request instead of each triggering a new one. 355 fh_options = dict(scan_storage_options) 356 fh_options["default_cache_type"] = "readahead" 357 fh_options["default_block_size"] = 4096 358 fh = fsspec.open(file_path, "rb", **fh_options).open() 359 try: 360 size = int(fh.info().get("size", 0) or 0) 361 except Exception: 362 size = 0 363 364 # ------------------------------------------------------------------ # 365 # 1. Full-index cache (populated by unfiltered grib2io.open calls) # 366 # ------------------------------------------------------------------ # 367 full_cache_key = hashlib.sha1((file_path + str(size)).encode("ASCII")).hexdigest() 368 full_cache_path = os.path.join(cache_root, f"{full_cache_key}.grib2ioidx") 369 if os.path.exists(full_cache_path): 370 with builtins.open(full_cache_path, "rb") as cf: 371 index = pickle.load(cf) 372 msgs = msgs_from_index(index, filehandle=fh) 373 fh.close() 374 return index, msgs 375 376 # ------------------------------------------------------------------ # 377 # 2. Filter-specific partial-index cache # 378 # ------------------------------------------------------------------ # 379 filter_repr = ":".join(f"{k}={v}" for k, v in sorted(self.filters.items())) 380 filtered_cache_key = hashlib.sha1((file_path + str(size) + ":" + filter_repr).encode("ASCII")).hexdigest() 381 filtered_cache_path = os.path.join(cache_root, f"{filtered_cache_key}.grib2ioidx") 382 if os.path.exists(filtered_cache_path): 383 with builtins.open(filtered_cache_path, "rb") as cf: 384 index = pickle.load(cf) 385 msgs = msgs_from_index(index, filehandle=fh) 386 fh.close() 387 return index, msgs 388 389 # ------------------------------------------------------------------ # 390 # 3. Remote grib2io index sidecar (.grib2ioidx) # 391 # ------------------------------------------------------------------ # 392 # grib2io publishes its own binary index alongside the GRIB2 file. 393 # This is the most efficient index format — it contains the full 394 # parsed section offsets/sizes and avoids any header reads. Check 395 # for it before falling back to the wgrib2 text .idx sidecar. 396 grib2io_idx_url = file_path + ".grib2ioidx" 397 try: 398 with fsspec.open(grib2io_idx_url, "rb", **scan_storage_options) as gf: 399 index = pickle.load(gf) 400 msgs = msgs_from_index(index, filehandle=fh) 401 fh.close() 402 # Cache locally so subsequent calls are instant. 403 try: 404 os.makedirs(cache_root, exist_ok=True) 405 with builtins.open(full_cache_path, "wb") as cf: 406 pickle.dump(index, cf) 407 except Exception: 408 pass 409 return index, msgs 410 except Exception: 411 pass 412 413 # ------------------------------------------------------------------ # 414 # 4. wgrib2 .idx sidecar pre-filtering # 415 # ------------------------------------------------------------------ # 416 idx_url = file_path + ".idx" 417 idx_fetch_ok = False 418 filtered_offsets: List[int] = [] 419 try: 420 with fsspec.open(idx_url, "r", **scan_storage_options) as idxf: 421 filtered_offsets = _prefilter_idx_offsets(idxf, shortname_filter, self.filters) 422 idx_fetch_ok = True 423 except Exception: 424 pass 425 426 if idx_fetch_ok: 427 if not filtered_offsets: 428 # shortName simply does not appear in this file. 429 fh.close() 430 return {}, [] 431 index = build_index(fh, offsets=filtered_offsets) 432 msgs = msgs_from_index(index, filehandle=fh) 433 fh.close() 434 # Persist the partial index so the next call is instant. 435 try: 436 os.makedirs(cache_root, exist_ok=True) 437 with builtins.open(filtered_cache_path, "wb") as cf: 438 pickle.dump(index, cf) 439 except Exception: 440 pass 441 return index, msgs 442 443 # ------------------------------------------------------------------ # 444 # 5. Fall back: let grib2io.open build the full index (slow on first # 445 # call, but saves to grib2io's own cache for future calls). # 446 # ------------------------------------------------------------------ # 447 fh.close() 448 with grib2io.open(file_path, save_index=True, use_index=True, **scan_storage_options) as f: 449 return f._index, list(f) 450 451 def _scan_file( 452 self, 453 file_path: str, 454 file_uri: str, 455 all_var_messages: Dict[str, list], 456 ) -> None: 457 """Scan a single GRIB2 file and collect message entries.""" 458 if _is_local_path(file_path): 459 with grib2io.open(file_path, save_index=False, use_index=True) as f: 460 index = f._index 461 msgs = list(f) 462 else: 463 scan_storage_options = _remote_scan_storage_options(file_path, self.storage_options) 464 shortname_filter = self.filters.get("shortName") if self.filters else None 465 # Normalise list/tuple to a set so _prefilter_idx_offsets can do a 466 # fast membership test; leave scalar strings as-is. 467 if isinstance(shortname_filter, (list, tuple)): 468 shortname_filter = set(shortname_filter) 469 # Fast path: resolve the index from a sidecar (.grib2ioidx or the 470 # wgrib2 .idx) instead of fetching headers for every message. This 471 # works whether or not a shortName filter is given: when shortName 472 # is present it is combined with any other filters; when it is 473 # absent, other filters (e.g. typeOfFirstFixedSurface/level) are 474 # still applied to the .idx, and the .grib2ioidx sidecar yields the 475 # full parsed index with no header reads at all. 476 index, msgs = self._build_remote_index_filtered(file_path, shortname_filter, scan_storage_options) 477 478 n_msgs = len(msgs) 479 480 # GRIB2 submessages may omit Section 3 and inherit the grid definition 481 # of the message before them, so index["section3"] is not necessarily 482 # parallel to the message list and must not be indexed by the message 483 # counter. Resolve each message to its own Section 3 entry first. 484 sec3_map = _build_section3_map(index, n_msgs) 485 486 for i in range(n_msgs): 487 msg = msgs[i] 488 489 # Apply filters 490 if not self._matches_filters(msg): 491 continue 492 493 sec_offsets = index["sectionOffset"][i] 494 sec_sizes = index["sectionSize"][i] 495 bmapflag = index["bmapflag"][i] 496 497 # Section 7 offset and length 498 sec7_offset = sec_offsets[7] 499 sec7_length = sec_sizes[7] 500 501 # Section 5 (data representation) — always present 502 sec5_offset = sec_offsets[5] 503 sec5_length = sec_sizes[5] 504 505 # Section 6 (bitmap) — always present (6 bytes when no bitmap) 506 sec6_length = sec_sizes[6] 507 # Offset only needed for the old bitmap-conditional path (kept for reference) 508 sec6_offset = sec_offsets[6] if bmapflag in {0, 254} else None 509 510 # Build a composite variable key that includes the surface type 511 # to avoid grouping messages with different surface types together. 512 # This mirrors how the xarray backend requires filtering to a 513 # single typeOfFirstFixedSurface. 514 var_name = str(msg.shortName) 515 type_of_first_fixed_surface = msg.typeOfFirstFixedSurface 516 if hasattr(type_of_first_fixed_surface, "value"): 517 toffs_val = type_of_first_fixed_surface.value 518 else: 519 toffs_val = type_of_first_fixed_surface 520 521 # Also include typeOfGeneratingProcess and 522 # productDefinitionTemplateNumber to disambiguate further 523 # (same approach as xarray backend's required_uniques) 524 pdtn = msg.productDefinitionTemplateNumber 525 if hasattr(pdtn, "value"): 526 pdtn_val = pdtn.value 527 else: 528 pdtn_val = pdtn 529 530 type_of_second_fixed_surface = msg.typeOfSecondFixedSurface 531 if hasattr(type_of_second_fixed_surface, "value"): 532 tosfs_val = type_of_second_fixed_surface.value 533 else: 534 tosfs_val = type_of_second_fixed_surface 535 536 # Group key: shortName + surface type + pdtn + second surface type, 537 # plus the probability threshold for probability products. Those 538 # commonly share every other identifying field -- NBM PTYPE carries 539 # four messages that differ only in their category bounds -- so 540 # without the threshold they would collide into one variable. 541 group_key = (var_name, int(toffs_val), int(pdtn_val), int(tosfs_val), _probability_key(msg)) 542 543 entry = _MsgEntry( 544 msg=msg, 545 file_uri=file_uri, 546 sec5_offset=sec5_offset, 547 sec5_length=sec5_length, 548 sec6_length=sec6_length, 549 sec7_offset=sec7_offset, 550 sec7_length=sec7_length, 551 sec6_offset=sec6_offset, 552 bmapflag=bmapflag, 553 index_section3=index["section3"][sec3_map[i]], 554 index_section5=index["section5"][i], 555 ) 556 557 all_var_messages.setdefault(group_key, []).append(entry) 558 559 def _matches_filters(self, msg) -> bool: 560 """Check if a message matches all user-supplied filters. 561 562 Filter values may be: 563 564 * **scalar** – exact equality (``{"shortName": "TMP"}``) 565 * **list / tuple / set** – membership test 566 (``{"level": [500, 850, 250]}``) 567 * **slice** – inclusive range test 568 (``{"level": slice(500, 850)}``) 569 """ 570 for key, value in self.filters.items(): 571 msg_val = getattr(msg, key, None) 572 if msg_val is None: 573 return False 574 # Unwrap Grib2Metadata wrapper objects 575 if hasattr(msg_val, "value"): 576 msg_val = msg_val.value 577 if isinstance(value, slice): 578 lo = value.start if value.start is not None else float("-inf") 579 hi = value.stop if value.stop is not None else float("inf") 580 try: 581 if not (lo <= msg_val <= hi): 582 return False 583 except TypeError: 584 return False 585 elif isinstance(value, (list, tuple, set)): 586 if msg_val not in value: 587 return False 588 else: 589 if msg_val != value: 590 return False 591 return True 592 593 # ------------------------------------------------------------------ 594 # Variable reference building 595 # ------------------------------------------------------------------ 596 597 def _build_variable_refs( 598 self, 599 var_name: str, 600 msg_entries: list, 601 refs: Dict[str, Any], 602 dim_coord_registry: Optional[Dict[str, list]] = None, 603 ) -> None: 604 """Build all Zarr refs for a single variable.""" 605 # Derive surface-type-specific level dim name (mirrors xarray_backend). 606 level_base = _level_dim_name(msg_entries[0].msg) 607 dim_mapping = _map_messages_to_dimensions(msg_entries, level_dim_name=level_base) 608 609 dim_names = dim_mapping["dim_names"] # ordered, using base names 610 dim_values = dim_mapping["dim_values"] # base name -> sorted unique values 611 msg_index_map = dim_mapping["msg_index_map"] 612 duplicate_entry_indices = dim_mapping["duplicate_entry_indices"] 613 614 # Resolve every non-spatial dimension against the shared registry, not 615 # just the level one. Two variables can disagree on the extent of any 616 # of them -- NBM, for example, emits CWASP over 7 percentiles and CAPE 617 # over 3 -- and whichever is written second would otherwise overwrite 618 # the first's coordinate array, leaving the manifest unopenable. 619 rename = _resolve_dim_names(dim_names, dim_values, dim_coord_registry) 620 emitted = [rename[d] for d in dim_names] 621 622 # Representative message for metadata 623 rep_msg = msg_entries[0].msg 624 625 # Compute shape (ensure plain Python ints for JSON serialization) 626 shape = [len(dim_values[d]) for d in dim_names] + [int(rep_msg.ny), int(rep_msg.nx)] 627 chunks = [1] * len(dim_names) + [int(rep_msg.ny), int(rep_msg.nx)] 628 629 # Build .zarray 630 codec_config = _build_codec_config(msg_entries[0]) 631 zarray = _build_zarray_metadata(rep_msg, shape, chunks, codec_config) 632 refs[f"{var_name}/.zarray"] = json.dumps(zarray) 633 634 # Build .zattrs 635 dim_labels = emitted + ["y", "x"] 636 zattrs = _build_zattrs(rep_msg, dim_labels) 637 638 # ``level`` and ``valueOfFirstFixedSurface`` describe the representative 639 # message only. When several messages are folded into one array along a 640 # level dimension they are correct for the first level and wrong for 641 # every other one, so a consumer reading attributes instead of the 642 # coordinate array is misled (e.g. a 41-level pressure array labelled 643 # "0.01 mb"). Drop them here and let the level coordinate carry the 644 # information instead -- see _build_coord_refs / _level_coord_attrs. 645 n_levels = len(dim_values.get(level_base, ())) 646 if n_levels > 1: 647 for _key in ("level", "valueOfFirstFixedSurface"): 648 zattrs.pop(_key, None) 649 650 refs[f"{var_name}/.zattrs"] = json.dumps(zattrs) 651 652 # Build data chunk refs 653 for dim_tuple, entry_idx in msg_index_map.items(): 654 entry = msg_entries[entry_idx] 655 dim_indices = [] 656 for i, d in enumerate(dim_names): 657 val = dim_tuple[i] 658 idx = list(dim_values[d]).index(val) 659 dim_indices.append(idx) 660 661 chunk_key = _build_chunk_key(var_name, dim_indices) 662 663 # Store a combined reference covering sections 5+6+7 so that the 664 # codec can parse the per-chunk data representation template (sec5) 665 # and bitmap (sec6) dynamically. Sections 5, 6, and 7 are always 666 # contiguous in the GRIB2 byte stream. 667 refs[chunk_key] = [ 668 entry.file_uri, 669 entry.sec5_offset, 670 entry.sec5_length + entry.sec6_length + entry.sec7_length, 671 ] 672 673 # Build coordinate arrays as inline base64-encoded refs. The emitted 674 # name may be suffixed, so pass the base name too: the value encoding 675 # and CF attributes are chosen from what the dimension *is*, not from 676 # what it ended up being called. 677 for d in dim_names: 678 _build_coord_refs( 679 rename[d], 680 dim_values[d], 681 refs, 682 msg=rep_msg, 683 is_level=(d == level_base), 684 base_name=d, 685 ) 686 687 # Re-emit any messages whose identifying metadata exactly collided 688 # with an earlier message as a sibling variable, so no message's 689 # bytes are silently dropped from the manifest. smartinit, for 690 # example, encodes a 1-bit binary field whose PDT is byte-identical 691 # to the real surface TMP message; only the packing (Section 5) 692 # differs. Which message is "the" variable and which is the 693 # duplicate is file-order and cannot be determined from metadata, 694 # hence the warning telling consumers to inspect both. 695 if duplicate_entry_indices: 696 dup_entries = [msg_entries[i] for i in duplicate_entry_indices] 697 m = re.match(r"^(.*)_dup(\d*)$", var_name) 698 if m: 699 dup_name = f"{m.group(1)}_dup{int(m.group(2) or 1) + 1}" 700 else: 701 dup_name = f"{var_name}_dup" 702 warnings.warn( 703 f"{len(dup_entries)} message(s) share identical identifying " 704 f"metadata with an earlier '{var_name}' message; emitting " 705 f"them as '{dup_name}'. The GRIB2 encoding of these " 706 f"products is ambiguous; inspect both variables to " 707 f"determine which is the intended field." 708 ) 709 self._build_variable_refs(dup_name, dup_entries, refs, dim_coord_registry) 710 711 # ------------------------------------------------------------------ 712 # Manifest access 713 # ------------------------------------------------------------------ 714 715 @property 716 def manifest(self) -> Optional[dict]: 717 """The generated manifest, or ``None`` if :meth:`generate` has not 718 been called yet.""" 719 return self._manifest
Generate Kerchunk v1 reference manifests from GRIB2 files.
Parameters
- file_paths (str or list of str): One or more GRIB2 file paths (local paths or URIs).
- filters (dict, optional):
Filter GRIB2 messages by metadata attributes. Keys can be any
Grib2Messageattribute name (e.g.shortName,leadTime). - storage_options (dict, optional):
Extra options passed to
fsspec.openfor remote URIs (e.g.{"anon": True}for public S3 buckets). - validate (bool, default True):
Check the finished manifest for internal consistency before returning
it, and raise
ValueErrorif any variable's dimension lengths disagree with the coordinate arrays it references. PassFalseto emit the manifest regardless.
ReferenceGenerator( file_paths: Union[str, List[str]], filters: Optional[Dict[str, Any]] = None, storage_options: Optional[Dict[str, Any]] = None, max_workers: Optional[int] = None, validate: bool = True)
137 def __init__( 138 self, 139 file_paths: Union[str, List[str]], 140 filters: Optional[Dict[str, Any]] = None, 141 storage_options: Optional[Dict[str, Any]] = None, 142 max_workers: Optional[int] = None, 143 validate: bool = True, 144 ): 145 _ensure_numcodecs() 146 147 if isinstance(file_paths, (str, os.PathLike)): 148 file_paths = [str(file_paths)] 149 else: 150 file_paths = [str(p) for p in file_paths] 151 152 # Validate file accessibility. 153 # Local filesystem paths must exist. URI inputs are handled by 154 # grib2io.open/fsspec at scan time and should not be rejected here. 155 for fp in file_paths: 156 if _is_local_path(fp) and not os.path.isfile(fp): 157 raise FileNotFoundError(f"GRIB2 file not found: {fp}") 158 159 self.file_paths = file_paths 160 self.filters = filters or {} 161 self.storage_options = storage_options or {} 162 self.max_workers = max_workers 163 self.validate = validate 164 self._manifest: Optional[dict] = None
def
generate(self) -> dict:
166 def generate(self) -> dict: 167 """Scan files and produce a Kerchunk v1 reference manifest. 168 169 Returns 170 ------- 171 dict 172 Kerchunk reference spec v1 dict with keys ``"version"`` and 173 ``"refs"``. 174 """ 175 refs: Dict[str, Any] = {} 176 177 # .zgroup at root 178 refs[".zgroup"] = json.dumps({"zarr_format": 2}) 179 180 # Collect all messages across files, keyed by variable group 181 # group_key = (shortName, typeOfFirstFixedSurface, pdtn, typeOfSecondFixedSurface, probability_key) 182 # This ensures messages with different surface types are not mixed. 183 all_var_messages: Dict[tuple, list] = {} 184 185 n_files = len(self.file_paths) 186 use_parallel = self.max_workers != 1 and n_files > 1 and not _is_local_path(self.file_paths[0]) 187 188 if use_parallel: 189 import concurrent.futures 190 191 workers = self.max_workers or min(n_files, 8) 192 193 def _scan_one(file_path): 194 file_uri = _file_uri(file_path) 195 local_msgs: Dict[tuple, list] = {} 196 self._scan_file(file_path, file_uri, local_msgs) 197 return local_msgs 198 199 with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool: 200 futures = {pool.submit(_scan_one, fp): fp for fp in self.file_paths} 201 for future in concurrent.futures.as_completed(futures): 202 fp = futures[future] 203 try: 204 local_msgs = future.result() 205 for key, entries in local_msgs.items(): 206 all_var_messages.setdefault(key, []).extend(entries) 207 except Exception as e: 208 raise ValueError(f"Failed to parse GRIB2 file '{fp}': {e}") from e 209 else: 210 for file_path in self.file_paths: 211 file_uri = _file_uri(file_path) 212 try: 213 self._scan_file(file_path, file_uri, all_var_messages) 214 except Exception as e: 215 raise ValueError(f"Failed to parse GRIB2 file '{file_path}': {e}") from e 216 217 # For each variable group, map messages to dimensions and build refs. 218 # Track used variable names to handle collisions (same shortName 219 # but different surface types). 220 # Also track level coord name -> level values so that the same surface 221 # type but different level extents get disambiguated names (mirrors 222 # how the xarray backend keeps each surface type in its own Dataset). 223 used_var_names: Dict[str, int] = {} 224 # Emitted dimension name -> coordinate values written under it. Shared 225 # across every variable so that two variables needing different values 226 # for the same dimension get distinct names instead of one silently 227 # overwriting the other's coordinate array. 228 dim_coord_registry: Dict[str, list] = {} 229 for group_key, msg_entries in all_var_messages.items(): 230 var_name = group_key[0] # shortName is the first element 231 # Probability products are named for their threshold so each one 232 # is self-describing, e.g. PTYPE_prob_between_1p0_and_2p0. 233 prob_key = group_key[4] 234 if prob_key is not None: 235 var_name = f"{var_name}_{_probability_suffix(prob_key)}" 236 if var_name in used_var_names: 237 used_var_names[var_name] += 1 238 zarr_var_name = f"{var_name}_{used_var_names[var_name]}" 239 else: 240 used_var_names[var_name] = 0 241 zarr_var_name = var_name 242 self._build_variable_refs(zarr_var_name, msg_entries, refs, dim_coord_registry) 243 244 # Build latitude/longitude coordinate arrays from the grid definition. 245 # All messages are assumed to share the same grid (required by the 246 # xarray backend too), so we use the first available message. 247 if all_var_messages: 248 first_entries = next(iter(all_var_messages.values())) 249 rep_msg = first_entries[0].msg 250 _build_latlon_coord_refs(rep_msg, refs) 251 252 # Root-level dataset metadata (CF global attributes + GRIB2 253 # provenance from Sections 0/1/4). Without this, a manifest 254 # separated from its filename carries no record of which model, 255 # center, or cycle it describes. 256 refs[".zattrs"] = json.dumps(_build_root_zattrs(rep_msg)) 257 258 if self.validate: 259 problems = _validate_refs(refs) 260 if problems: 261 raise ValueError(_format_validation_errors(problems)) 262 263 self._manifest = {"version": 1, "refs": refs} 264 return self._manifest
Scan files and produce a Kerchunk v1 reference manifest.
Returns
- dict: Kerchunk reference spec v1 dict with keys
"version"and"refs".
def
to_json(self, output_path: str) -> None:
266 def to_json(self, output_path: str) -> None: 267 """Serialize the manifest to a JSON file. 268 269 Parameters 270 ---------- 271 output_path : str 272 Path to the output JSON file. 273 """ 274 if self._manifest is None: 275 self.generate() 276 with open(output_path, "w") as f: 277 json.dump(self._manifest, f)
Serialize the manifest to a JSON file.
Parameters
- output_path (str): Path to the output JSON file.
def
to_parquet(self, output_path: str) -> None:
279 def to_parquet(self, output_path: str) -> None: 280 """Serialize the manifest to a Parquet reference store. 281 282 Parameters 283 ---------- 284 output_path : str 285 Path to the output Parquet directory. 286 """ 287 _ensure_kerchunk() 288 if self._manifest is None: 289 self.generate() 290 291 import fsspec 292 from fsspec.implementations.reference import LazyReferenceMapper 293 294 fs, _ = fsspec.core.url_to_fs(output_path) 295 out = LazyReferenceMapper.create(output_path, fs=fs, record_size=100_000, engine="pyarrow") 296 refs = self._manifest.get("refs", self._manifest) 297 for k in sorted(refs): 298 out[k] = refs[k] 299 out.flush()
Serialize the manifest to a Parquet reference store.
Parameters
- output_path (str): Path to the output Parquet directory.