grib2io
Introduction
grib2io is a Python package that provides an interface to the NCEP GRIB2 C (g2c) library for the purpose of reading and writing WMO GRIdded Binary, Edition 2 (GRIB2) messages. A physical file can contain one or more GRIB2 messages.
GRIB2 file IO is performed directly in Python. The unpacking/packing of GRIB2 integer, coded metadata and data sections is performed by the g2c library functions via the g2clib Cython extension module. The decoding/encoding of GRIB2 metadata is translated into more descriptive, plain language metadata by providing a mapping of the integer coded metadata to the appropriate GRIB2 code tables. The NCEP GRIB2 code tables are a part of the grib2io package.
Index File
As of v2.6.0, grib2io provides the capability to create (and read) an index file for a GRIB2 file. The index file contents are specific to Python and grib2io in that pickle is used to dump the index dictionary to file. Using index files can dramatically improve performance in situations where the same file will be read multiple times. The index file name is the original GRIB2 file name with a hash string appended, followed by the file extension, .grib2ioidx. The hash string is the SHA-1 of the GRIB2 file name and the file size. For example, GRIB2 file,
gfs.t00z.pgrb2.1p00.f024
when opened, grib2io will generate an index file with the following name,
gfs.t00z.pgrb2.1p00.f024_0422a93bfd6d095bd0a942ba5e9fe42e76050123.grib2ioidx
By default, grib2io will generate an index file or use an existing one. The generation and usage
of a grib2io index file can be turned off by providing kwargs use_index=False and/or
save_index=False in grib2io.open().
Interpolation
As of v2.4.0, spatial interpolation via NCEPLIPS-ip Fortran library is now a part of the grib2io package. Previously, interpolation was handled by a separate component package, grib2io-interp, which is now deprecated. grib2io-interp provided interpolation via a F2PY-generated interface to NCEPLIBS-ip, which has become difficult since the removal of distutils from Python 3.12+.
NCEPLIBS-ip interpolation Fortran subroutines contain the BIND(C) attribute which
provides an equivalent C-interface. grib2io now provides a Cython-based interface, iplib,
to these Fortran subroutines via their C-interface. If NCEPLIBS-ip was built with
OpenMP support, iplib will provide functions for getting and setting the number of
OpenMP threads.
Xarray Backend
grib2io provides a Xarray backend engine so that many GRIB2 messages can be represented as N-dimensional DataArray objects and collected along common coordinates as Datasets or DataTrees. The Xarray backend engine API is experimental and is subject to change without backward compatibility.
Tutorials
The following Jupyter Notebooks are available as tutorials:
1from ._grib2io import ( 2 open, 3 interpolate, 4 interpolate_to_stations, 5 Grib2Message, 6 _Grib2Message, 7 Grib2GridDef, 8 msgs_from_index, 9 __doc__, 10) 11from . import tables, templates, utils 12 13try: 14 from . import __config__ 15 16 __version__ = __config__.grib2io_version 17 has_interpolation = __config__.has_interpolation 18 has_openmp_support = __config__.has_openmp_support 19 g2c_static = __config__.g2c_static 20 g2c_library = __config__.g2c_library 21 ip_static = __config__.ip_static 22 ip_library = __config__.ip_library 23 extra_objects = __config__.extra_objects 24except ImportError: 25 pass 26 27from .g2clib import __version__ as __g2clib_version__ 28from .g2clib import _has_jpeg 29from .g2clib import _has_png 30from .g2clib import _has_aec 31 32from .tables.originating_centers import _ncep_grib2_table_version 33 34__all__ = [ 35 "open", 36 "show_config", 37 "interpolate", 38 "interpolate_to_stations", 39 "tables", 40 "templates", 41 "utils", 42 "codecs", 43 "kerchunk", 44 "Grib2Message", 45 "_Grib2Message", 46 "Grib2GridDef", 47 "msgs_from_index", 48 "__doc__", 49] 50 51has_jpeg_support = bool(_has_jpeg) 52has_png_support = bool(_has_png) 53has_aec_support = bool(_has_aec) 54 55ncep_grib2_table_version = _ncep_grib2_table_version 56g2c_version = __g2clib_version__ 57 58# --------------------------------------------------------------------------- 59# Lazy imports for optional-dependency modules 60# --------------------------------------------------------------------------- 61# These modules are only imported when explicitly accessed (e.g., 62# ``grib2io.codecs``, ``grib2io.kerchunk``). 63# This keeps the core package lightweight and avoids ImportError when 64# optional dependencies (numcodecs, kerchunk) are not installed. 65 66_LAZY_MODULES = {"codecs", "kerchunk"} 67 68# Eagerly import codecs so zarr v3 and numcodecs codec registrations fire 69# on `import grib2io`, enabling VirtualiZarr and kerchunk to work out of 70# the box without requiring `import grib2io.codecs` separately. 71try: 72 from . import codecs as _codecs_module # noqa: F401 73except ImportError: 74 pass # zarr/numcodecs not installed; codec registration deferred 75 76 77def __getattr__(name: str): 78 if name in _LAZY_MODULES: 79 import importlib 80 81 module = importlib.import_module(f".{name}", __name__) 82 globals()[name] = module 83 return module 84 raise AttributeError(f"module {__name__!r} has no attribute {name!r}") 85 86 87def show_config(): 88 """Print grib2io build configuration information.""" 89 print(f"grib2io version {__version__} Configuration:") 90 print("") 91 print(f"NCEPLIBS-g2c library version: {__g2clib_version__}") 92 print(f"\tStatic library: {g2c_static}") 93 print(f"\tLibrary: {g2c_library}") 94 print(f"\tJPEG compression support: {has_jpeg_support}") 95 print(f"\tPNG compression support: {has_png_support}") 96 print(f"\tAEC compression support: {has_aec_support}") 97 print("") 98 print(f"NCEPLIPS-ip support: {has_interpolation}") 99 print(f"\tStatic library: {ip_static}") 100 print(f"\tLibrary: {ip_library}") 101 print(f"\tOpenMP support: {has_openmp_support}") 102 print("") 103 print("Static libs:") 104 for lib in extra_objects: 105 print(f"\t{lib}") 106 print("") 107 print(f"NCEP GRIB2 Table Version: {_ncep_grib2_table_version}")
119class open: 120 """ 121 GRIB2 File Object. 122 123 This class can accommodate a physical file with one or more GRIB2 124 messages or a bytes object containing a GRIB2 messages. 125 126 A physical file can contain one or more GRIB2 messages. When instantiated, 127 class `grib2io.open`, the file named `filename` is opened for reading (`mode 128 = 'r'`) and is automatically indexed. The indexing procedure reads some of 129 the GRIB2 metadata for all GRIB2 Messages. A GRIB2 Message may contain 130 submessages whereby Section 2-7 can be repeated. grib2io accommodates for 131 this by flattening any GRIB2 submessages into multiple individual messages. 132 133 It is important to note that GRIB2 files from some Meteorological agencies 134 contain other data than GRIB2 messages. GRIB2 files from ECMWF can contain 135 GRIB1 and GRIB2 messages. grib2io checks for these and safely ignores them. 136 137 Attributes 138 ---------- 139 closed : bool 140 `True` is file handle is close; `False` otherwise. 141 current_message : int 142 Current position of the file in units of GRIB2 Messages. (read only) 143 indexfile : str 144 Index file for the GRIB2 file. 145 levels : tuple 146 Tuple containing a unique list of wgrib2-formatted level/layer strings. 147 messages : int 148 Count of GRIB2 Messages contained in the file. 149 mode : str 150 File IO mode of opening the file. 151 name : str 152 Full path name of the GRIB2 file. 153 save_index : bool 154 Whether to save a pickle-based index file for the GRIB2 file. Default is `True`. 155 size : int 156 Size of the file in units of bytes. 157 use_index 158 Whether to use an existing pickle-based index file for the GRIB2 file. Default is `True`. 159 variables : tuple 160 Tuple containing a unique list of variable short names (i.e. GRIB2 161 abbreviation names). 162 """ 163 164 __slots__ = ( 165 "_fileid", 166 "_filehandle", 167 "_hasindex", 168 "_index", 169 "_msgs", 170 "_pos", 171 "closed", 172 "current_message", 173 "indexfile", 174 "messages", 175 "mode", 176 "name", 177 "size", 178 "save_index", 179 "use_index", 180 ) 181 182 def __init__( 183 self, 184 filename: Union[bytes, str, Path, IO], 185 mode: Literal["r", "w", "x"] = "r", 186 *, 187 save_index=True, 188 use_index=True, 189 _xarray_backend=False, 190 **kwargs, 191 ): 192 """ 193 Initialize GRIB2 File object instance. 194 195 Parameters 196 ---------- 197 filename 198 File path containing GRIB2 messages OR bytes OR file-like object. 199 mode 200 File access mode where "r" opens the files for reading only; "w" 201 opens the file for overwriting and "x" for writing to a new file. 202 save_index 203 Whether to save a pickle-based index file for the GRIB2 file. Default is True. 204 205 .. versionadded:: 2.6.0 206 use_index 207 Whether to use an existing pickle-based index file for the GRIB2 file. Default is True. 208 209 .. versionadded:: 2.6.0 210 """ 211 212 # All write modes are read/write; all modes are binary. 213 if mode in ("a", "x", "w"): 214 mode += "+" 215 mode = mode + "b" 216 217 self._hasindex = False 218 self.indexfile = None 219 self.mode = mode 220 self.save_index = save_index 221 self.size = 0 222 self.use_index = use_index 223 224 if isinstance(filename, bytes): 225 if "r" not in self.mode: 226 raise ValueError( 227 "Invalid mode for bytes input: GRIB2 data supplied as bytes is read-only. Use mode='r' or provide a filename instead." 228 ) 229 230 self.current_message = 0 231 if filename[:2] == _GZIP_HEADER: 232 filename = gzip.decompress(filename) 233 if filename[:4] + filename[-4:] != b"GRIB7777": 234 raise ValueError("Invalid GRIB bytes") 235 self._filehandle = BytesIO(filename) 236 self.name = "<in-memory-file>" 237 self.size = len(filename) 238 self._fileid = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 239 self._index = build_index(self._filehandle) 240 self._msgs = msgs_from_index(self._index, filehandle=self._filehandle) 241 self.messages = len(self._msgs) 242 243 elif all(hasattr(filename, attr) for attr in ("read", "seek", "tell")): 244 # Handle file-like objects (including S3File, etc.) 245 self.current_message = 0 246 self._filehandle = filename 247 self.name = getattr(filename, "name", getattr(filename, "path", filename.__repr__())) 248 try: 249 self.size = self._filehandle.info().get("size", 0) 250 except (AttributeError, TypeError): 251 self.size = 0 252 self._fileid = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 253 254 if "r" in self.mode: 255 self.indexfile = f"{self.name}.grib2ioidx" 256 idx_loaded = False 257 if self.use_index: 258 try: 259 import fsspec 260 261 with fsspec.open(self.indexfile, "rb") as f: 262 self._index = pickle.load(f) 263 idx_loaded = True 264 self._hasindex = True 265 except Exception: 266 pass 267 if not idx_loaded: 268 self._index = build_index(self._filehandle) 269 self._msgs = msgs_from_index(self._index, filehandle=self._filehandle) 270 self.messages = len(self._msgs) 271 272 else: 273 self.current_message = 0 274 self.name = str(filename) 275 is_remote = isinstance(filename, str) and "://" in filename 276 if is_remote: 277 import fsspec 278 279 self._filehandle = fsspec.open(filename, mode=mode, **kwargs).open() 280 self.name = filename 281 try: 282 self.size = self._filehandle.info().get("size", 0) 283 except (AttributeError, TypeError): 284 self.size = 0 285 self._fileid = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 286 else: 287 self.name = os.path.abspath(filename) 288 if "r" in mode: 289 self._filehandle = builtins.open(filename, mode=mode) 290 # Some GRIB2 files are gzipped, so check for that here, but 291 # raise error when using xarray backend. 292 # Gzip files contain a 2-byte header b'\x1f\x8b'. 293 if self._filehandle.read(2) == _GZIP_HEADER: 294 self._filehandle.close() 295 if _xarray_backend: 296 raise RuntimeError("Gzip GRIB2 files are not supported by the Xarray backend.") 297 self._filehandle = gzip.open(filename, mode=mode) 298 else: 299 self._filehandle.seek(0) 300 else: 301 self._filehandle = builtins.open(filename, mode=mode) 302 fstat = os.stat(self.name) 303 self.size = fstat.st_size 304 self._fileid = hashlib.sha1((self.name + str(fstat.st_ino) + str(self.size)).encode("ASCII")).hexdigest() 305 306 if "r" in self.mode: 307 index_paths = [f"{self.name}_{self._fileid}.grib2ioidx", f"{self.name}.grib2ioidx"] 308 idx_paths = [f"{self.name}.idx"] 309 idx_loaded = False 310 remote_index_cache_path = None 311 if is_remote: 312 cache_root = os.path.join(os.path.expanduser("~"), ".cache", "grib2io") 313 cache_key = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 314 remote_index_cache_path = os.path.join(cache_root, f"{cache_key}.grib2ioidx") 315 if self.use_index: 316 if is_remote and remote_index_cache_path and os.path.exists(remote_index_cache_path): 317 try: 318 with builtins.open(remote_index_cache_path, "rb") as f: 319 self._index = pickle.load(f) 320 self.indexfile = remote_index_cache_path 321 idx_loaded = True 322 self._hasindex = True 323 except Exception: 324 idx_loaded = False 325 for idx_path in index_paths: 326 if idx_loaded: 327 break 328 try: 329 if is_remote: 330 import fsspec 331 332 with fsspec.open(idx_path, "rb", **kwargs) as f: 333 self._index = pickle.load(f) 334 else: 335 if os.path.exists(idx_path): 336 with builtins.open(idx_path, "rb") as f: 337 self._index = pickle.load(f) 338 else: 339 continue 340 self.indexfile = idx_path 341 idx_loaded = True 342 self._hasindex = True 343 break 344 except Exception: 345 continue 346 if not idx_loaded: 347 for idx_path in idx_paths: 348 try: 349 if is_remote: 350 import fsspec 351 352 with fsspec.open(idx_path, "r", **kwargs) as f: 353 offsets = _parse_wgrib2_idx(f) 354 else: 355 if os.path.exists(idx_path): 356 with builtins.open(idx_path, "r") as f: 357 offsets = _parse_wgrib2_idx(f) 358 else: 359 continue 360 if offsets: 361 self._index = build_index(self._filehandle, offsets=offsets) 362 self.indexfile = idx_path 363 idx_loaded = True 364 self._hasindex = True 365 break 366 except Exception: 367 continue 368 if is_remote and idx_loaded and self.save_index and remote_index_cache_path: 369 if self.indexfile != remote_index_cache_path: 370 try: 371 os.makedirs(os.path.dirname(remote_index_cache_path), exist_ok=True) 372 serialize_index(self._index, remote_index_cache_path) 373 except Exception: 374 pass 375 if not idx_loaded: 376 self._index = build_index(self._filehandle) 377 self.indexfile = index_paths[0] 378 if self.save_index: 379 try: 380 if is_remote and remote_index_cache_path: 381 os.makedirs(os.path.dirname(remote_index_cache_path), exist_ok=True) 382 serialize_index(self._index, remote_index_cache_path) 383 self.indexfile = remote_index_cache_path 384 else: 385 serialize_index(self._index, self.indexfile) 386 except Exception as e: 387 warnings.warn(f"index was not serialized for future use: {e}") 388 self._msgs = msgs_from_index(self._index, filehandle=self._filehandle) 389 self.messages = len(self._msgs) 390 elif "w" or "x" in self.mode: 391 self.messages = 0 392 self.current_message = None 393 394 self.closed = self._filehandle.closed 395 396 def __delete__(self, instance): 397 self.close() 398 del self._index 399 400 def __enter__(self): 401 return self 402 403 def __exit__(self, atype, value, traceback): 404 self.close() 405 406 def __iter__(self): 407 yield from self._msgs 408 409 def __len__(self): 410 return self.messages 411 412 def __repr__(self): 413 strings = [] 414 for k in self.__slots__: 415 if k.startswith("_"): 416 continue 417 strings.append("%s = %s\n" % (k, eval("self." + k))) 418 return "".join(strings) 419 420 def __getitem__(self, key): 421 if isinstance(key, int): 422 if abs(key) >= len(self._msgs): 423 raise IndexError("index out of range") 424 else: 425 return self._msgs[key] 426 elif isinstance(key, str): 427 return self.select(shortName=key) 428 elif isinstance(key, slice): 429 return self._msgs[key] 430 elif isinstance(key, (list, tuple, set)): 431 if len(key) == 0: 432 return iter(self._msgs) 433 indices = sorted(key) if isinstance(key, set) else key 434 435 def _iter_msgs(): 436 for i in indices: 437 if not isinstance(i, int): 438 raise TypeError(f"indices must be integers; got {type(i).__name__}") 439 if abs(i) >= len(self._msgs): 440 raise IndexError(f"index out of range: {i}") 441 yield self._msgs[i] 442 443 return _iter_msgs() 444 else: 445 raise KeyError("Key must be an integer, slice, GRIB2 variable shortName, or an iterable of integer indices.") 446 447 @property 448 def levels(self): 449 """Provides a unique tuple of level strings.""" 450 if self._hasindex: 451 return tuple(sorted(set([msg.level for msg in self._msgs]))) 452 else: 453 return None 454 455 @property 456 def variables(self): 457 """Provides a unique tuple of variable shortName strings.""" 458 if self._hasindex: 459 return tuple(sorted(set([msg.shortName for msg in self._msgs]))) 460 else: 461 return None 462 463 def close(self): 464 """Close the file handle.""" 465 if not self._filehandle.closed: 466 self.messages = 0 467 self.current_message = 0 468 self._filehandle.close() 469 self.closed = self._filehandle.closed 470 471 def read(self, size: Optional[int] = None): 472 """ 473 Read size amount of GRIB2 messages from the current position. 474 475 If no argument is given, then size is None and all messages are returned 476 from the current position in the file. This read method follows the 477 behavior of Python's builtin open() function, but whereas that operates 478 on units of bytes, we operate on units of GRIB2 messages. 479 480 Parameters 481 ---------- 482 size: default=None 483 The number of GRIB2 messages to read from the current position. If 484 no argument is give, the default value is None and remainder of 485 the file is read. 486 487 Returns 488 ------- 489 read 490 ``Grib2Message`` object when size = 1 or a list of Grib2Messages 491 when size > 1. 492 """ 493 if size is not None and size < 0: 494 size = None 495 if size is None or size > 1: 496 start = self.tell() 497 stop = self.messages if size is None else start + size 498 if size is None: 499 self.current_message = self.messages - 1 500 else: 501 self.current_message += size 502 return self._msgs[slice(start, stop, 1)] 503 elif size == 1: 504 self.current_message += 1 505 return self._msgs[self.current_message] 506 else: 507 None 508 509 def seek(self, pos: int): 510 """ 511 Set the position within the file in units of GRIB2 messages. 512 513 Parameters 514 ---------- 515 pos 516 The GRIB2 Message number to set the file pointer to. 517 """ 518 if self._hasindex: 519 self._filehandle.seek(self._index["sectionOffset"][0][pos]) 520 self.current_message = pos 521 522 def tell(self): 523 """Returns the position of the file in units of GRIB2 Messages.""" 524 return self.current_message 525 526 def select(self, **kwargs): 527 """Select GRIB2 messages by `Grib2Message` attributes.""" 528 # TODO: Added ability to process multiple values for each keyword (attribute) 529 idxs = [] 530 nkeys = len(kwargs.keys()) 531 for k, v in kwargs.items(): 532 for m in self._msgs: 533 if hasattr(m, k) and getattr(m, k) == v: 534 idxs.append(m._msgnum) 535 idxs = np.array(idxs, dtype=np.int32) 536 return [self._msgs[i] for i in [ii[0] for ii in collections.Counter(idxs).most_common() if ii[1] == nkeys]] 537 538 def write(self, msg): 539 """ 540 Writes GRIB2 message object to file. 541 542 Parameters 543 ---------- 544 msg 545 GRIB2 message objects to write to file. 546 """ 547 if isinstance(msg, list): 548 for m in msg: 549 self.write(m) 550 return 551 552 if issubclass(msg.__class__, _Grib2Message): 553 # TODO: We can consider letting pack return packed bytes instead of associating with message object 554 if hasattr(msg, "_msg"): 555 # write already packed bytes 556 self._filehandle.write(msg._msg) 557 else: 558 # Check if modified data is present 559 has_unpacked_data = msg._data_ref is not None and msg._data_ref() is not None 560 if msg._signature == msg._generate_signature() and not has_unpacked_data and hasattr(msg._ondiskarray, "filehandle"): 561 # if msg._signature == msg._generate_signature() and msg._data is None and hasattr(msg._ondiskarray, "filehandle"): 562 # write unchanged message from input 563 offset = msg._ondiskarray.filehandle.tell() 564 msg._ondiskarray.filehandle.seek(msg._ondiskarray.offset) 565 self._filehandle.write(msg._ondiskarray.filehandle.read(msg.section0[-1])) 566 msg._ondiskarray.filehandle.seek(offset) 567 else: 568 msg.pack() 569 self._filehandle.write(msg._msg) 570 self.size = os.path.getsize(self.name) 571 self.messages += 1 572 else: 573 raise TypeError("msg must be a Grib2Message object.") 574 return 575 576 def flush(self): 577 """Flush the file object buffer.""" 578 self._filehandle.flush() 579 580 def levels_by_var(self, name: str): 581 """ 582 Return a list of level strings given a variable shortName. 583 584 Parameters 585 ---------- 586 name 587 Grib2Message variable shortName 588 589 Returns 590 ------- 591 levels_by_var 592 A list of unique level strings. 593 """ 594 return list(sorted(set([msg.level for msg in self.select(shortName=name)]))) 595 596 def vars_by_level(self, level: str): 597 """ 598 Return a list of variable shortName strings given a level. 599 600 Parameters 601 ---------- 602 level 603 Grib2Message variable level 604 605 Returns 606 ------- 607 vars_by_level 608 A list of unique variable shortName strings. 609 """ 610 return list(sorted(set([msg.shortName for msg in self.select(level=level)])))
GRIB2 File Object.
This class can accommodate a physical file with one or more GRIB2 messages or a bytes object containing a GRIB2 messages.
A physical file can contain one or more GRIB2 messages. When instantiated,
class grib2io.open, the file named filename is opened for reading (mode
= 'r') and is automatically indexed. The indexing procedure reads some of
the GRIB2 metadata for all GRIB2 Messages. A GRIB2 Message may contain
submessages whereby Section 2-7 can be repeated. grib2io accommodates for
this by flattening any GRIB2 submessages into multiple individual messages.
It is important to note that GRIB2 files from some Meteorological agencies contain other data than GRIB2 messages. GRIB2 files from ECMWF can contain GRIB1 and GRIB2 messages. grib2io checks for these and safely ignores them.
Attributes
- closed (bool):
Trueis file handle is close;Falseotherwise. - current_message (int): Current position of the file in units of GRIB2 Messages. (read only)
- indexfile (str): Index file for the GRIB2 file.
- levels (tuple): Tuple containing a unique list of wgrib2-formatted level/layer strings.
- messages (int): Count of GRIB2 Messages contained in the file.
- mode (str): File IO mode of opening the file.
- name (str): Full path name of the GRIB2 file.
- save_index (bool):
Whether to save a pickle-based index file for the GRIB2 file. Default is
True. - size (int): Size of the file in units of bytes.
- use_index: Whether to use an existing pickle-based index file for the GRIB2 file. Default is
True. - variables (tuple): Tuple containing a unique list of variable short names (i.e. GRIB2 abbreviation names).
182 def __init__( 183 self, 184 filename: Union[bytes, str, Path, IO], 185 mode: Literal["r", "w", "x"] = "r", 186 *, 187 save_index=True, 188 use_index=True, 189 _xarray_backend=False, 190 **kwargs, 191 ): 192 """ 193 Initialize GRIB2 File object instance. 194 195 Parameters 196 ---------- 197 filename 198 File path containing GRIB2 messages OR bytes OR file-like object. 199 mode 200 File access mode where "r" opens the files for reading only; "w" 201 opens the file for overwriting and "x" for writing to a new file. 202 save_index 203 Whether to save a pickle-based index file for the GRIB2 file. Default is True. 204 205 .. versionadded:: 2.6.0 206 use_index 207 Whether to use an existing pickle-based index file for the GRIB2 file. Default is True. 208 209 .. versionadded:: 2.6.0 210 """ 211 212 # All write modes are read/write; all modes are binary. 213 if mode in ("a", "x", "w"): 214 mode += "+" 215 mode = mode + "b" 216 217 self._hasindex = False 218 self.indexfile = None 219 self.mode = mode 220 self.save_index = save_index 221 self.size = 0 222 self.use_index = use_index 223 224 if isinstance(filename, bytes): 225 if "r" not in self.mode: 226 raise ValueError( 227 "Invalid mode for bytes input: GRIB2 data supplied as bytes is read-only. Use mode='r' or provide a filename instead." 228 ) 229 230 self.current_message = 0 231 if filename[:2] == _GZIP_HEADER: 232 filename = gzip.decompress(filename) 233 if filename[:4] + filename[-4:] != b"GRIB7777": 234 raise ValueError("Invalid GRIB bytes") 235 self._filehandle = BytesIO(filename) 236 self.name = "<in-memory-file>" 237 self.size = len(filename) 238 self._fileid = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 239 self._index = build_index(self._filehandle) 240 self._msgs = msgs_from_index(self._index, filehandle=self._filehandle) 241 self.messages = len(self._msgs) 242 243 elif all(hasattr(filename, attr) for attr in ("read", "seek", "tell")): 244 # Handle file-like objects (including S3File, etc.) 245 self.current_message = 0 246 self._filehandle = filename 247 self.name = getattr(filename, "name", getattr(filename, "path", filename.__repr__())) 248 try: 249 self.size = self._filehandle.info().get("size", 0) 250 except (AttributeError, TypeError): 251 self.size = 0 252 self._fileid = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 253 254 if "r" in self.mode: 255 self.indexfile = f"{self.name}.grib2ioidx" 256 idx_loaded = False 257 if self.use_index: 258 try: 259 import fsspec 260 261 with fsspec.open(self.indexfile, "rb") as f: 262 self._index = pickle.load(f) 263 idx_loaded = True 264 self._hasindex = True 265 except Exception: 266 pass 267 if not idx_loaded: 268 self._index = build_index(self._filehandle) 269 self._msgs = msgs_from_index(self._index, filehandle=self._filehandle) 270 self.messages = len(self._msgs) 271 272 else: 273 self.current_message = 0 274 self.name = str(filename) 275 is_remote = isinstance(filename, str) and "://" in filename 276 if is_remote: 277 import fsspec 278 279 self._filehandle = fsspec.open(filename, mode=mode, **kwargs).open() 280 self.name = filename 281 try: 282 self.size = self._filehandle.info().get("size", 0) 283 except (AttributeError, TypeError): 284 self.size = 0 285 self._fileid = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 286 else: 287 self.name = os.path.abspath(filename) 288 if "r" in mode: 289 self._filehandle = builtins.open(filename, mode=mode) 290 # Some GRIB2 files are gzipped, so check for that here, but 291 # raise error when using xarray backend. 292 # Gzip files contain a 2-byte header b'\x1f\x8b'. 293 if self._filehandle.read(2) == _GZIP_HEADER: 294 self._filehandle.close() 295 if _xarray_backend: 296 raise RuntimeError("Gzip GRIB2 files are not supported by the Xarray backend.") 297 self._filehandle = gzip.open(filename, mode=mode) 298 else: 299 self._filehandle.seek(0) 300 else: 301 self._filehandle = builtins.open(filename, mode=mode) 302 fstat = os.stat(self.name) 303 self.size = fstat.st_size 304 self._fileid = hashlib.sha1((self.name + str(fstat.st_ino) + str(self.size)).encode("ASCII")).hexdigest() 305 306 if "r" in self.mode: 307 index_paths = [f"{self.name}_{self._fileid}.grib2ioidx", f"{self.name}.grib2ioidx"] 308 idx_paths = [f"{self.name}.idx"] 309 idx_loaded = False 310 remote_index_cache_path = None 311 if is_remote: 312 cache_root = os.path.join(os.path.expanduser("~"), ".cache", "grib2io") 313 cache_key = hashlib.sha1((self.name + str(self.size)).encode("ASCII")).hexdigest() 314 remote_index_cache_path = os.path.join(cache_root, f"{cache_key}.grib2ioidx") 315 if self.use_index: 316 if is_remote and remote_index_cache_path and os.path.exists(remote_index_cache_path): 317 try: 318 with builtins.open(remote_index_cache_path, "rb") as f: 319 self._index = pickle.load(f) 320 self.indexfile = remote_index_cache_path 321 idx_loaded = True 322 self._hasindex = True 323 except Exception: 324 idx_loaded = False 325 for idx_path in index_paths: 326 if idx_loaded: 327 break 328 try: 329 if is_remote: 330 import fsspec 331 332 with fsspec.open(idx_path, "rb", **kwargs) as f: 333 self._index = pickle.load(f) 334 else: 335 if os.path.exists(idx_path): 336 with builtins.open(idx_path, "rb") as f: 337 self._index = pickle.load(f) 338 else: 339 continue 340 self.indexfile = idx_path 341 idx_loaded = True 342 self._hasindex = True 343 break 344 except Exception: 345 continue 346 if not idx_loaded: 347 for idx_path in idx_paths: 348 try: 349 if is_remote: 350 import fsspec 351 352 with fsspec.open(idx_path, "r", **kwargs) as f: 353 offsets = _parse_wgrib2_idx(f) 354 else: 355 if os.path.exists(idx_path): 356 with builtins.open(idx_path, "r") as f: 357 offsets = _parse_wgrib2_idx(f) 358 else: 359 continue 360 if offsets: 361 self._index = build_index(self._filehandle, offsets=offsets) 362 self.indexfile = idx_path 363 idx_loaded = True 364 self._hasindex = True 365 break 366 except Exception: 367 continue 368 if is_remote and idx_loaded and self.save_index and remote_index_cache_path: 369 if self.indexfile != remote_index_cache_path: 370 try: 371 os.makedirs(os.path.dirname(remote_index_cache_path), exist_ok=True) 372 serialize_index(self._index, remote_index_cache_path) 373 except Exception: 374 pass 375 if not idx_loaded: 376 self._index = build_index(self._filehandle) 377 self.indexfile = index_paths[0] 378 if self.save_index: 379 try: 380 if is_remote and remote_index_cache_path: 381 os.makedirs(os.path.dirname(remote_index_cache_path), exist_ok=True) 382 serialize_index(self._index, remote_index_cache_path) 383 self.indexfile = remote_index_cache_path 384 else: 385 serialize_index(self._index, self.indexfile) 386 except Exception as e: 387 warnings.warn(f"index was not serialized for future use: {e}") 388 self._msgs = msgs_from_index(self._index, filehandle=self._filehandle) 389 self.messages = len(self._msgs) 390 elif "w" or "x" in self.mode: 391 self.messages = 0 392 self.current_message = None 393 394 self.closed = self._filehandle.closed
Initialize GRIB2 File object instance.
Parameters
- filename: File path containing GRIB2 messages OR bytes OR file-like object.
- mode: File access mode where "r" opens the files for reading only; "w" opens the file for overwriting and "x" for writing to a new file.
- save_index: Whether to save a pickle-based index file for the GRIB2 file. Default is True.
New in version 2.6.0.
- use_index: Whether to use an existing pickle-based index file for the GRIB2 file. Default is True.
New in version 2.6.0.
447 @property 448 def levels(self): 449 """Provides a unique tuple of level strings.""" 450 if self._hasindex: 451 return tuple(sorted(set([msg.level for msg in self._msgs]))) 452 else: 453 return None
Provides a unique tuple of level strings.
455 @property 456 def variables(self): 457 """Provides a unique tuple of variable shortName strings.""" 458 if self._hasindex: 459 return tuple(sorted(set([msg.shortName for msg in self._msgs]))) 460 else: 461 return None
Provides a unique tuple of variable shortName strings.
463 def close(self): 464 """Close the file handle.""" 465 if not self._filehandle.closed: 466 self.messages = 0 467 self.current_message = 0 468 self._filehandle.close() 469 self.closed = self._filehandle.closed
Close the file handle.
471 def read(self, size: Optional[int] = None): 472 """ 473 Read size amount of GRIB2 messages from the current position. 474 475 If no argument is given, then size is None and all messages are returned 476 from the current position in the file. This read method follows the 477 behavior of Python's builtin open() function, but whereas that operates 478 on units of bytes, we operate on units of GRIB2 messages. 479 480 Parameters 481 ---------- 482 size: default=None 483 The number of GRIB2 messages to read from the current position. If 484 no argument is give, the default value is None and remainder of 485 the file is read. 486 487 Returns 488 ------- 489 read 490 ``Grib2Message`` object when size = 1 or a list of Grib2Messages 491 when size > 1. 492 """ 493 if size is not None and size < 0: 494 size = None 495 if size is None or size > 1: 496 start = self.tell() 497 stop = self.messages if size is None else start + size 498 if size is None: 499 self.current_message = self.messages - 1 500 else: 501 self.current_message += size 502 return self._msgs[slice(start, stop, 1)] 503 elif size == 1: 504 self.current_message += 1 505 return self._msgs[self.current_message] 506 else: 507 None
Read size amount of GRIB2 messages from the current position.
If no argument is given, then size is None and all messages are returned from the current position in the file. This read method follows the behavior of Python's builtin open() function, but whereas that operates on units of bytes, we operate on units of GRIB2 messages.
Parameters
- size (default=None): The number of GRIB2 messages to read from the current position. If no argument is give, the default value is None and remainder of the file is read.
Returns
- read:
Grib2Messageobject when size = 1 or a list of Grib2Messages when size > 1.
509 def seek(self, pos: int): 510 """ 511 Set the position within the file in units of GRIB2 messages. 512 513 Parameters 514 ---------- 515 pos 516 The GRIB2 Message number to set the file pointer to. 517 """ 518 if self._hasindex: 519 self._filehandle.seek(self._index["sectionOffset"][0][pos]) 520 self.current_message = pos
Set the position within the file in units of GRIB2 messages.
Parameters
- pos: The GRIB2 Message number to set the file pointer to.
522 def tell(self): 523 """Returns the position of the file in units of GRIB2 Messages.""" 524 return self.current_message
Returns the position of the file in units of GRIB2 Messages.
526 def select(self, **kwargs): 527 """Select GRIB2 messages by `Grib2Message` attributes.""" 528 # TODO: Added ability to process multiple values for each keyword (attribute) 529 idxs = [] 530 nkeys = len(kwargs.keys()) 531 for k, v in kwargs.items(): 532 for m in self._msgs: 533 if hasattr(m, k) and getattr(m, k) == v: 534 idxs.append(m._msgnum) 535 idxs = np.array(idxs, dtype=np.int32) 536 return [self._msgs[i] for i in [ii[0] for ii in collections.Counter(idxs).most_common() if ii[1] == nkeys]]
Select GRIB2 messages by Grib2Message attributes.
538 def write(self, msg): 539 """ 540 Writes GRIB2 message object to file. 541 542 Parameters 543 ---------- 544 msg 545 GRIB2 message objects to write to file. 546 """ 547 if isinstance(msg, list): 548 for m in msg: 549 self.write(m) 550 return 551 552 if issubclass(msg.__class__, _Grib2Message): 553 # TODO: We can consider letting pack return packed bytes instead of associating with message object 554 if hasattr(msg, "_msg"): 555 # write already packed bytes 556 self._filehandle.write(msg._msg) 557 else: 558 # Check if modified data is present 559 has_unpacked_data = msg._data_ref is not None and msg._data_ref() is not None 560 if msg._signature == msg._generate_signature() and not has_unpacked_data and hasattr(msg._ondiskarray, "filehandle"): 561 # if msg._signature == msg._generate_signature() and msg._data is None and hasattr(msg._ondiskarray, "filehandle"): 562 # write unchanged message from input 563 offset = msg._ondiskarray.filehandle.tell() 564 msg._ondiskarray.filehandle.seek(msg._ondiskarray.offset) 565 self._filehandle.write(msg._ondiskarray.filehandle.read(msg.section0[-1])) 566 msg._ondiskarray.filehandle.seek(offset) 567 else: 568 msg.pack() 569 self._filehandle.write(msg._msg) 570 self.size = os.path.getsize(self.name) 571 self.messages += 1 572 else: 573 raise TypeError("msg must be a Grib2Message object.") 574 return
Writes GRIB2 message object to file.
Parameters
- msg: GRIB2 message objects to write to file.
580 def levels_by_var(self, name: str): 581 """ 582 Return a list of level strings given a variable shortName. 583 584 Parameters 585 ---------- 586 name 587 Grib2Message variable shortName 588 589 Returns 590 ------- 591 levels_by_var 592 A list of unique level strings. 593 """ 594 return list(sorted(set([msg.level for msg in self.select(shortName=name)])))
Return a list of level strings given a variable shortName.
Parameters
- name: Grib2Message variable shortName
Returns
- levels_by_var: A list of unique level strings.
596 def vars_by_level(self, level: str): 597 """ 598 Return a list of variable shortName strings given a level. 599 600 Parameters 601 ---------- 602 level 603 Grib2Message variable level 604 605 Returns 606 ------- 607 vars_by_level 608 A list of unique variable shortName strings. 609 """ 610 return list(sorted(set([msg.shortName for msg in self.select(level=level)])))
Return a list of variable shortName strings given a level.
Parameters
- level: Grib2Message variable level
Returns
- vars_by_level: A list of unique variable shortName strings.
88def show_config(): 89 """Print grib2io build configuration information.""" 90 print(f"grib2io version {__version__} Configuration:") 91 print("") 92 print(f"NCEPLIBS-g2c library version: {__g2clib_version__}") 93 print(f"\tStatic library: {g2c_static}") 94 print(f"\tLibrary: {g2c_library}") 95 print(f"\tJPEG compression support: {has_jpeg_support}") 96 print(f"\tPNG compression support: {has_png_support}") 97 print(f"\tAEC compression support: {has_aec_support}") 98 print("") 99 print(f"NCEPLIPS-ip support: {has_interpolation}") 100 print(f"\tStatic library: {ip_static}") 101 print(f"\tLibrary: {ip_library}") 102 print(f"\tOpenMP support: {has_openmp_support}") 103 print("") 104 print("Static libs:") 105 for lib in extra_objects: 106 print(f"\t{lib}") 107 print("") 108 print(f"NCEP GRIB2 Table Version: {_ncep_grib2_table_version}")
Print grib2io build configuration information.
2021def interpolate( 2022 a, 2023 method: Union[int, str], 2024 grid_def_in, 2025 grid_def_out, 2026 method_options=None, 2027 num_threads=1, 2028): 2029 """ 2030 This is the module-level interpolation function. 2031 2032 This interfaces with the "d" version of[NCEPLIBS-ip library](https://github.com/NOAA-EMC/NCEPLIBS-ip) 2033 through grib2io's internal iplib Cython extension module. The "d" version 2034 defines 4-byte integers and 8-byte reals. 2035 2036 Parameters 2037 ---------- 2038 a : numpy.ndarray or tuple 2039 Input data. If `a` is a `numpy.ndarray`, scalar interpolation will be 2040 performed. If `a` is a `tuple`, then vector interpolation will be 2041 performed with the assumption that u = a[0] and v = a[1] and are both 2042 `numpy.ndarray`. 2043 2044 These data are expected to be in 2-dimensional form with shape (ny, nx) 2045 or 3-dimensional (:, ny, nx) where the 1st dimension represents another 2046 spatial, temporal, or classification (i.e. ensemble members) dimension. 2047 The function will properly flatten the (ny,nx) dimensions into (nx * ny) 2048 acceptable for input into the interpolation subroutines. If needed, these 2049 data will be converted to `np.float32`. 2050 method 2051 Interpolate method to use. This can either be an integer or string using 2052 the following mapping: 2053 2054 | Interpolate Scheme | Integer Value | 2055 | :---: | :---: | 2056 | 'bilinear' | 0 | 2057 | 'bicubic' | 1 | 2058 | 'neighbor' | 2 | 2059 | 'budget' | 3 | 2060 | 'spectral' | 4 | 2061 | 'neighbor-budget' | 6 | 2062 2063 grid_def_in : grib2io.Grib2GridDef 2064 Grib2GridDef object for the input grid. 2065 grid_def_out : grib2io.Grib2GridDef 2066 Grib2GridDef object for the output grid or station points. 2067 method_options : list of ints, optional 2068 Interpolation options. See the NCEPLIBS-ip documentation for 2069 more information on how these are used. 2070 num_threads : int, optional 2071 Number of OpenMP threads to use for interpolation. The default 2072 value is 1. If NCEPLIBS-ip and grib2io's iplib extension module 2073 was not built with OpenMP, then this keyword argument and value 2074 will have no impact. 2075 2076 Returns 2077 ------- 2078 interpolate 2079 Returns a `numpy.ndarray` of dtype `np.float32` when scalar interpolation 2080 is performed or a `tuple` of `numpy.ndarray`s when vector interpolation is 2081 performed with the assumptions that 0-index is the interpolated u and 2082 1-index is the interpolated v. 2083 """ 2084 2085 try: 2086 from . import iplib 2087 except ImportError: 2088 raise ImportError("NCEPLIBS-ip library not found. Interpolation is not available.") 2089 2090 prev_num_threads = 1 2091 try: 2092 prev_num_threads = iplib.openmp_get_num_threads() 2093 iplib.openmp_set_num_threads(num_threads) 2094 except AttributeError: 2095 pass 2096 2097 print(f"grib2io.interpolate thread report: OpenMP num threads = {iplib.openmp_get_num_threads()}") 2098 2099 if isinstance(method, int) and method not in _interp_schemes.values(): 2100 raise ValueError("Invalid interpolation method.") 2101 elif isinstance(method, str): 2102 if method in _interp_schemes.keys(): 2103 method = _interp_schemes[method] 2104 else: 2105 raise ValueError("Invalid interpolation method.") 2106 2107 if method_options is None: 2108 method_options = np.zeros((20), dtype=np.int32) 2109 if method in {3, 6}: 2110 method_options[0:2] = -1 2111 2112 mi = grid_def_in.npoints 2113 mo = grid_def_out.npoints 2114 2115 # Adjust shape of input array(s) 2116 a, newshp = _adjust_array_shape_for_interp(a, grid_def_in, grid_def_out) 2117 2118 # Call interpolation subroutines according to type of a. 2119 if isinstance(a, np.ndarray): 2120 # Scalar 2121 km = a.shape[0] 2122 if np.any(np.isnan(a)): 2123 ibi = np.ones((km), dtype=np.int32) 2124 li = np.where(np.isnan(a), 0, 1).astype(np.uint8) 2125 else: 2126 ibi = np.zeros((km), dtype=np.int32) 2127 li = np.zeros(a.shape, dtype=np.uint8) 2128 no, rlat, rlon, ibo, lo, go, iret = iplib.interpolate_scalar( 2129 method, 2130 method_options, 2131 grid_def_in.gdtn, 2132 np.array(grid_def_in.gdt, dtype=np.int32), 2133 grid_def_out.gdtn, 2134 np.array(grid_def_out.gdt, dtype=np.int32), 2135 mi, 2136 mo, 2137 km, 2138 ibi, 2139 li, 2140 a.astype(np.float64), 2141 ) 2142 out = np.where(lo == 0, np.nan, go).reshape(newshp) 2143 elif isinstance(a, tuple): 2144 # Vector 2145 km = a[0].shape[0] 2146 if np.any(np.isnan(a)): 2147 ibi = np.ones((km), dtype=np.int32) 2148 li = np.where(np.isnan(a), 0, 1).astype(np.uint8) 2149 else: 2150 ibi = np.zeros((km), dtype=np.int32) 2151 li = np.zeros(a[0].shape, dtype=np.uint8) 2152 no, rlat, rlon, crot, srot, ibo, lo, uo, vo, iret = iplib.interpolate_vector( 2153 method, 2154 method_options, 2155 grid_def_in.gdtn, 2156 np.array(grid_def_in.gdt, dtype=np.int32), 2157 grid_def_out.gdtn, 2158 np.array(grid_def_out.gdt, dtype=np.int32), 2159 mi, 2160 mo, 2161 km, 2162 ibi, 2163 li, 2164 a[0].astype(np.float64), 2165 a[1].astype(np.float64), 2166 ) 2167 uo = np.where(lo == 0, np.nan, uo).reshape(newshp) 2168 vo = np.where(lo == 0, np.nan, vo).reshape(newshp) 2169 out = (uo.astype(np.float32), vo.astype(np.float32)) 2170 2171 try: 2172 iplib.openmp_set_num_threads(prev_num_threads) 2173 except AttributeError: 2174 pass 2175 2176 return out
This is the module-level interpolation function.
This interfaces with the "d" version ofNCEPLIBS-ip library through grib2io's internal iplib Cython extension module. The "d" version defines 4-byte integers and 8-byte reals.
Parameters
a (numpy.ndarray or tuple): Input data. If
ais anumpy.ndarray, scalar interpolation will be performed. Ifais atuple, then vector interpolation will be performed with the assumption that u = a[0] and v = a[1] and are bothnumpy.ndarray.These data are expected to be in 2-dimensional form with shape (ny, nx) or 3-dimensional (:, ny, nx) where the 1st dimension represents another spatial, temporal, or classification (i.e. ensemble members) dimension. The function will properly flatten the (ny,nx) dimensions into (nx * ny) acceptable for input into the interpolation subroutines. If needed, these data will be converted to
np.float32.- method: Interpolate method to use. This can either be an integer or string using the following mapping:
| Interpolate Scheme | Integer Value |
|---|---|
| 'bilinear' | 0 |
| 'bicubic' | 1 |
| 'neighbor' | 2 |
| 'budget' | 3 |
| 'spectral' | 4 |
| 'neighbor-budget' | 6 |
- grid_def_in (grib2io.Grib2GridDef): Grib2GridDef object for the input grid.
- grid_def_out (grib2io.Grib2GridDef): Grib2GridDef object for the output grid or station points.
- method_options (list of ints, optional): Interpolation options. See the NCEPLIBS-ip documentation for more information on how these are used.
- num_threads (int, optional): Number of OpenMP threads to use for interpolation. The default value is 1. If NCEPLIBS-ip and grib2io's iplib extension module was not built with OpenMP, then this keyword argument and value will have no impact.
Returns
- interpolate: Returns a
numpy.ndarrayof dtypenp.float32when scalar interpolation is performed or atupleofnumpy.ndarrays when vector interpolation is performed with the assumptions that 0-index is the interpolated u and 1-index is the interpolated v.
2179def interpolate_to_stations( 2180 a, 2181 method: Union[int, str], 2182 grid_def_in, 2183 lats, 2184 lons, 2185 method_options=None, 2186 num_threads=1, 2187): 2188 """ 2189 Module-level interpolation function for interpolation to stations. 2190 2191 Interfaces with the "d" version of [NCEPLIBS-ip library](https://github.com/NOAA-EMC/NCEPLIBS-ip) 2192 via grib2io's iplib Cython exntension module. It supports scalar and 2193 vector interpolation according to the type of object a. 2194 2195 Parameters 2196 ---------- 2197 a : numpy.ndarray or tuple 2198 Input data. If `a` is a `numpy.ndarray`, scalar interpolation will be 2199 performed. If `a` is a `tuple`, then vector interpolation will be 2200 performed with the assumption that u = a[0] and v = a[1] and are both 2201 `numpy.ndarray`. 2202 2203 These data are expected to be in 2-dimensional form with shape (ny, nx) 2204 or 3-dimensional (:, ny, nx) where the 1st dimension represents another 2205 spatial, temporal, or classification (i.e. ensemble members) dimension. 2206 The function will properly flatten the (ny,nx) dimensions into (nx * ny) 2207 acceptable for input into the interpolation subroutines. If needed, these 2208 data will be converted to `np.float32`. 2209 method 2210 Interpolate method to use. This can either be an integer or string using 2211 the following mapping: 2212 2213 | Interpolate Scheme | Integer Value | 2214 | :---: | :---: | 2215 | 'bilinear' | 0 | 2216 | 'bicubic' | 1 | 2217 | 'neighbor' | 2 | 2218 | 'budget' | 3 | 2219 | 'spectral' | 4 | 2220 | 'neighbor-budget' | 6 | 2221 2222 grid_def_in : grib2io.Grib2GridDef 2223 Grib2GridDef object for the input grid. 2224 lats : numpy.ndarray or list 2225 Latitudes for station points 2226 lons : numpy.ndarray or list 2227 Longitudes for station points 2228 method_options : list of ints, optional 2229 Interpolation options. See the NCEPLIBS-ip documentation for 2230 more information on how these are used. 2231 num_threads : int, optional 2232 Number of OpenMP threads to use for interpolation. The default 2233 value is 1. If NCEPLIBS-ip and grib2io's iplib extension module 2234 was not built with OpenMP, then this keyword argument and value 2235 will have no impact. 2236 2237 Returns 2238 ------- 2239 interpolate_to_stations 2240 Returns a `numpy.ndarray` of dtype `np.float32` when scalar 2241 interpolation is performed or a `tuple` of `numpy.ndarray`s 2242 when vector interpolation is performed with the assumptions 2243 that 0-index is the interpolated u and 1-index is the 2244 interpolated v. 2245 """ 2246 try: 2247 from . import iplib 2248 except ImportError: 2249 raise ImportError("NCEPLIBS-ip library not found. Interpolation is not available.") 2250 2251 # Define function to apply mask when stations are outside grid domain 2252 def _reshape_and_mask_post_interp(a, shape, mask): 2253 a = a.reshape(shape) 2254 if a.shape[-1] != mask.shape[0]: 2255 raise ValueError("Station mask length does not match interpolated data.") 2256 a[..., mask] = np.nan 2257 return a 2258 2259 prev_num_threads = 1 2260 try: 2261 prev_num_threads = iplib.openmp_get_num_threads() 2262 iplib.openmp_set_num_threads(num_threads) 2263 except AttributeError: 2264 pass 2265 2266 if isinstance(method, int) and method not in _interp_schemes.values(): 2267 raise ValueError("Invalid interpolation method.") 2268 elif isinstance(method, str): 2269 if method in _interp_schemes.keys(): 2270 method = _interp_schemes[method] 2271 else: 2272 raise ValueError("Invalid interpolation method.") 2273 2274 if method_options is None: 2275 method_options = np.zeros((20), dtype=np.int32) 2276 if method in {3, 6}: 2277 method_options[0:2] = -1 2278 2279 # Check lats and lons 2280 if isinstance(lats, list): 2281 nlats = len(lats) 2282 elif isinstance(lats, np.ndarray) and len(lats.shape) == 1: 2283 nlats = lats.shape[0] 2284 else: 2285 raise ValueError("Station latitudes must be a list or 1-D NumPy array.") 2286 if isinstance(lons, list): 2287 nlons = len(lons) 2288 elif isinstance(lons, np.ndarray) and len(lons.shape) == 1: 2289 nlons = lons.shape[0] 2290 else: 2291 raise ValueError("Station longitudes must be a list or 1-D NumPy array.") 2292 if nlats != nlons: 2293 raise ValueError("Station lats and lons must be same size.") 2294 2295 mi = grid_def_in.npoints 2296 mo = nlats 2297 2298 # Adjust shape of input array(s) 2299 a, newshp = _adjust_array_shape_for_interp_stations(a, grid_def_in, mo) 2300 2301 # Use gdtn = -1 for stations and an empty template array 2302 gdtn_out = -1 2303 gdt_out = np.zeros((200), dtype=np.int32) 2304 2305 # Before we interpolate, get the grid coordinates for stations. 2306 xloc, yloc = utils.latlon_to_ij( 2307 grid_def_in.gdtn, 2308 grid_def_in.gdt, 2309 np.array(lats, dtype=np.float32), 2310 np.array(lons, dtype=np.float32), 2311 ) 2312 xloc_mask = np.where(np.isnan(xloc), True, False) 2313 yloc_mask = np.where(np.isnan(yloc), True, False) 2314 mask = xloc_mask & yloc_mask 2315 2316 # Call interpolation subroutines according to type of a. 2317 if isinstance(a, np.ndarray): 2318 # Scalar 2319 km = a.shape[0] 2320 ibi = np.zeros((km), dtype=np.int32) 2321 li = np.zeros(a.shape, dtype=np.uint8) 2322 no, rlat, rlon, ibo, lo, go, iret = iplib.interpolate_scalar( 2323 method, 2324 method_options, 2325 grid_def_in.gdtn, 2326 np.array(grid_def_in.gdt, dtype=np.int32), 2327 gdtn_out, 2328 gdt_out, 2329 mi, 2330 mo, 2331 km, 2332 ibi, 2333 li, 2334 a.astype(np.float64), 2335 lats=np.array(lats, dtype=np.float64), 2336 lons=np.array(lons, dtype=np.float64), 2337 ) 2338 out = _reshape_and_mask_post_interp(go, newshp, mask) 2339 2340 elif isinstance(a, tuple): 2341 # Vector 2342 km = a[0].shape[0] 2343 ibi = np.zeros((km), dtype=np.int32) 2344 li = np.zeros(a[0].shape, dtype=np.uint8) 2345 no, rlat, rlon, crot, srot, ibo, lo, uo, vo, iret = iplib.interpolate_vector( 2346 method, 2347 method_options, 2348 grid_def_in.gdtn, 2349 np.array(grid_def_in.gdt, dtype=np.int32), 2350 gdtn_out, 2351 gdt_out, 2352 mi, 2353 mo, 2354 km, 2355 ibi, 2356 li, 2357 a[0].astype(np.float64), 2358 a[1].astype(np.float64), 2359 lats=np.array(lats, dtype=np.float64), 2360 lons=np.array(lons, dtype=np.float64), 2361 ) 2362 out = ( 2363 _reshape_and_mask_post_interp(uo.astype(np.float32), newshp, mask), 2364 _reshape_and_mask_post_interp(vo.astype(np.float32), newshp, mask), 2365 ) 2366 2367 try: 2368 iplib.openmp_set_num_threads(prev_num_threads) 2369 except AttributeError: 2370 pass 2371 2372 return out
Module-level interpolation function for interpolation to stations.
Interfaces with the "d" version of NCEPLIBS-ip library via grib2io's iplib Cython exntension module. It supports scalar and vector interpolation according to the type of object a.
Parameters
a (numpy.ndarray or tuple): Input data. If
ais anumpy.ndarray, scalar interpolation will be performed. Ifais atuple, then vector interpolation will be performed with the assumption that u = a[0] and v = a[1] and are bothnumpy.ndarray.These data are expected to be in 2-dimensional form with shape (ny, nx) or 3-dimensional (:, ny, nx) where the 1st dimension represents another spatial, temporal, or classification (i.e. ensemble members) dimension. The function will properly flatten the (ny,nx) dimensions into (nx * ny) acceptable for input into the interpolation subroutines. If needed, these data will be converted to
np.float32.- method: Interpolate method to use. This can either be an integer or string using the following mapping:
| Interpolate Scheme | Integer Value |
|---|---|
| 'bilinear' | 0 |
| 'bicubic' | 1 |
| 'neighbor' | 2 |
| 'budget' | 3 |
| 'spectral' | 4 |
| 'neighbor-budget' | 6 |
- grid_def_in (grib2io.Grib2GridDef): Grib2GridDef object for the input grid.
- lats (numpy.ndarray or list): Latitudes for station points
- lons (numpy.ndarray or list): Longitudes for station points
- method_options (list of ints, optional): Interpolation options. See the NCEPLIBS-ip documentation for more information on how these are used.
- num_threads (int, optional): Number of OpenMP threads to use for interpolation. The default value is 1. If NCEPLIBS-ip and grib2io's iplib extension module was not built with OpenMP, then this keyword argument and value will have no impact.
Returns
- interpolate_to_stations: Returns a
numpy.ndarrayof dtypenp.float32when scalar interpolation is performed or atupleofnumpy.ndarrays when vector interpolation is performed with the assumptions that 0-index is the interpolated u and 1-index is the interpolated v.
726class Grib2Message: 727 """ 728 Creation class for a GRIB2 message. 729 730 This class returns a dynamically-created Grib2Message object that 731 inherits from `_Grib2Message` and grid, product, data representation 732 template classes according to the template numbers for the respective 733 sections. If `section3`, `section4`, or `section5` are omitted, then 734 the appropriate keyword arguments for the template number `gdtn=`, 735 `pdtn=`, or `drtn=` must be provided. 736 737 Parameters 738 ---------- 739 section0 740 GRIB2 section 0 array. 741 section1 742 GRIB2 section 1 array. 743 section2 744 Local Use section data. 745 section3 746 GRIB2 section 3 array. 747 section4 748 GRIB2 section 4 array. 749 section5 750 GRIB2 section 5 array. 751 752 Returns 753 ------- 754 Msg 755 A dynamically-create Grib2Message object that inherits from 756 _Grib2Message, a grid definition template class, product 757 definition template class, and a data representation template 758 class. 759 """ 760 761 def __new__( 762 self, 763 section0: NDArray = np.array([struct.unpack(">I", b"GRIB")[0], 0, 0, 2, 0]), 764 section1: NDArray = np.zeros((13), dtype=np.int64), 765 section2: Optional[bytes] = None, 766 section3: Optional[NDArray] = None, 767 section4: Optional[NDArray] = None, 768 section5: Optional[NDArray] = None, 769 *args, 770 **kwargs, 771 ): 772 if np.all(section1 == 0): 773 try: 774 # Python >= 3.10 775 section1[5:11] = datetime.datetime.fromtimestamp(0, datetime.UTC).timetuple()[:6] 776 except AttributeError: 777 # Python < 3.10 778 section1[5:11] = datetime.datetime.utcfromtimestamp(0).timetuple()[:6] 779 780 bases = list() 781 if section3 is None: 782 if "gdtn" in kwargs.keys(): 783 gdtn = kwargs["gdtn"] 784 Gdt = templates.gdt_class_by_gdtn(gdtn) 785 bases.append(Gdt) 786 section3 = np.zeros((Gdt._len + 5), dtype=np.int64) 787 section3[4] = gdtn 788 else: 789 raise ValueError("Must provide GRIB2 Grid Definition Template Number or section 3 array") 790 else: 791 gdtn = section3[4] 792 Gdt = templates.gdt_class_by_gdtn(gdtn) 793 bases.append(Gdt) 794 795 if section4 is None: 796 if "pdtn" in kwargs.keys(): 797 pdtn = kwargs["pdtn"] 798 Pdt = templates.pdt_class_by_pdtn(pdtn) 799 bases.append(Pdt) 800 section4 = np.zeros((Pdt._len + 2), dtype=np.int64) 801 section4[1] = pdtn 802 else: 803 raise ValueError("Must provide GRIB2 Production Definition Template Number or section 4 array") 804 else: 805 pdtn = section4[1] 806 Pdt = templates.pdt_class_by_pdtn(pdtn) 807 bases.append(Pdt) 808 809 if section5 is None: 810 if "drtn" in kwargs.keys(): 811 drtn = kwargs["drtn"] 812 Drt = templates.drt_class_by_drtn(drtn) 813 bases.append(Drt) 814 section5 = np.zeros((Drt._len + 2), dtype=np.int64) 815 section5[1] = drtn 816 else: 817 raise ValueError("Must provide GRIB2 Data Representation Template Number or section 5 array") 818 else: 819 drtn = section5[1] 820 Drt = templates.drt_class_by_drtn(drtn) 821 bases.append(Drt) 822 823 # attempt to use existing Msg class if it has already been made with gdtn,pdtn,drtn combo 824 try: 825 Msg = _msg_class_store[f"{gdtn}:{pdtn}:{drtn}"] 826 except KeyError: 827 828 @dataclass(init=False, repr=False) 829 class Msg(_Grib2Message, *bases): 830 pass 831 832 _msg_class_store[f"{gdtn}:{pdtn}:{drtn}"] = Msg 833 834 return Msg(section0, section1, section2, section3, section4, section5, *args)
Creation class for a GRIB2 message.
This class returns a dynamically-created Grib2Message object that
inherits from _Grib2Message and grid, product, data representation
template classes according to the template numbers for the respective
sections. If section3, section4, or section5 are omitted, then
the appropriate keyword arguments for the template number gdtn=,
pdtn=, or drtn= must be provided.
Parameters
- section0: GRIB2 section 0 array.
- section1: GRIB2 section 1 array.
- section2: Local Use section data.
- section3: GRIB2 section 3 array.
- section4: GRIB2 section 4 array.
- section5: GRIB2 section 5 array.
Returns
- Msg: A dynamically-create Grib2Message object that inherits from _Grib2Message, a grid definition template class, product definition template class, and a data representation template class.
837@dataclass 838class _Grib2Message: 839 """ 840 GRIB2 Message base class. 841 """ 842 843 # GRIB2 Sections 844 section0: NDArray = field(init=True, repr=False) 845 section1: NDArray = field(init=True, repr=False) 846 section2: bytes = field(init=True, repr=False) 847 section3: NDArray = field(init=True, repr=False) 848 section4: NDArray = field(init=True, repr=False) 849 section5: NDArray = field(init=True, repr=False) 850 bitMapFlag: templates.Grib2Metadata = field(init=True, repr=False, default=255) 851 852 # Section 0 looked up attributes 853 indicatorSection: NDArray = field(init=False, repr=False, default=templates.IndicatorSection()) 854 discipline: templates.Grib2Metadata = field(init=False, repr=False, default=templates.Discipline()) 855 856 # Section 1 looked up attributes 857 identificationSection: NDArray = field(init=False, repr=False, default=templates.IdentificationSection()) 858 originatingCenter: templates.Grib2Metadata = field(init=False, repr=False, default=templates.OriginatingCenter()) 859 originatingSubCenter: templates.Grib2Metadata = field(init=False, repr=False, default=templates.OriginatingSubCenter()) 860 masterTableInfo: templates.Grib2Metadata = field(init=False, repr=False, default=templates.MasterTableInfo()) 861 localTableInfo: templates.Grib2Metadata = field(init=False, repr=False, default=templates.LocalTableInfo()) 862 significanceOfReferenceTime: templates.Grib2Metadata = field(init=False, repr=False, default=templates.SignificanceOfReferenceTime()) 863 year: int = field(init=False, repr=False, default=templates.Year()) 864 month: int = field(init=False, repr=False, default=templates.Month()) 865 day: int = field(init=False, repr=False, default=templates.Day()) 866 hour: int = field(init=False, repr=False, default=templates.Hour()) 867 minute: int = field(init=False, repr=False, default=templates.Minute()) 868 second: int = field(init=False, repr=False, default=templates.Second()) 869 refDate: datetime.datetime = field(init=False, repr=False, default=templates.RefDate()) 870 productionStatus: templates.Grib2Metadata = field(init=False, repr=False, default=templates.ProductionStatus()) 871 typeOfData: templates.Grib2Metadata = field(init=False, repr=False, default=templates.TypeOfData()) 872 873 # Section 3 looked up common attributes. Other looked up attributes are available according 874 # to the Grid Definition Template. 875 gridDefinitionSection: NDArray = field(init=False, repr=False, default=templates.GridDefinitionSection()) 876 sourceOfGridDefinition: int = field(init=False, repr=False, default=templates.SourceOfGridDefinition()) 877 numberOfDataPoints: int = field(init=False, repr=False, default=templates.NumberOfDataPoints()) 878 interpretationOfListOfNumbers: templates.Grib2Metadata = field(init=False, repr=False, default=templates.InterpretationOfListOfNumbers()) 879 gridDefinitionTemplateNumber: templates.Grib2Metadata = field(init=False, repr=False, default=templates.GridDefinitionTemplateNumber()) 880 gridDefinitionTemplate: list = field(init=False, repr=False, default=templates.GridDefinitionTemplate()) 881 _earthparams: dict = field(init=False, repr=False, default=templates.EarthParams()) 882 _dxsign: float = field(init=False, repr=False, default=templates.DxSign()) 883 _dysign: float = field(init=False, repr=False, default=templates.DySign()) 884 _llscalefactor: float = field(init=False, repr=False, default=templates.LLScaleFactor()) 885 _lldivisor: float = field(init=False, repr=False, default=templates.LLDivisor()) 886 _xydivisor: float = field(init=False, repr=False, default=templates.XYDivisor()) 887 shapeOfEarth: templates.Grib2Metadata = field(init=False, repr=False, default=templates.ShapeOfEarth()) 888 earthShape: str = field(init=False, repr=False, default=templates.EarthShape()) 889 earthRadius: float = field(init=False, repr=False, default=templates.EarthRadius()) 890 earthMajorAxis: float = field(init=False, repr=False, default=templates.EarthMajorAxis()) 891 earthMinorAxis: float = field(init=False, repr=False, default=templates.EarthMinorAxis()) 892 resolutionAndComponentFlags: list = field(init=False, repr=False, default=templates.ResolutionAndComponentFlags()) 893 ny: int = field(init=False, repr=False, default=templates.Ny()) 894 nx: int = field(init=False, repr=False, default=templates.Nx()) 895 scanModeFlags: list = field(init=False, repr=False, default=templates.ScanModeFlags()) 896 projParameters: dict = field(init=False, repr=False, default=templates.ProjParameters()) 897 898 # Section 4 899 productDefinitionTemplateNumber: templates.Grib2Metadata = field(init=False, repr=False, default=templates.ProductDefinitionTemplateNumber()) 900 productDefinitionTemplate: NDArray = field(init=False, repr=False, default=templates.ProductDefinitionTemplate()) 901 902 # Section 5 looked up common attributes. Other looked up attributes are 903 # available according to the Data Representation Template. 904 numberOfPackedValues: int = field(init=False, repr=False, default=templates.NumberOfPackedValues()) 905 dataRepresentationTemplateNumber: templates.Grib2Metadata = field(init=False, repr=False, default=templates.DataRepresentationTemplateNumber()) 906 dataRepresentationTemplate: list = field(init=False, repr=False, default=templates.DataRepresentationTemplate()) 907 typeOfValues: templates.Grib2Metadata = field(init=False, repr=False, default=templates.TypeOfValues()) 908 909 def __copy__(self): 910 """Shallow copy""" 911 new = Grib2Message( 912 self.section0, 913 self.section1, 914 self.section2, 915 self.section3, 916 self.section4, 917 drtn=self.drtn, # section5=self.section5, 918 bitMapFlag=self.bitMapFlag.value, 919 ) 920 # Preserve on-disk array reference for on-demand decoding 921 new._ondiskarray = self._ondiskarray 922 new._msgnum = self._msgnum 923 new._deflist = self._deflist 924 new._coordlist = self._coordlist 925 new._auto_nans = self._auto_nans 926 927 # Share the weak reference to data if already decoded 928 new._data_ref = self._data_ref 929 new.bitmap = self.bitmap 930 return new 931 932 def __deepcopy__(self, memo): 933 """Deep copy""" 934 new = Grib2Message( 935 np.copy(self.section0), 936 np.copy(self.section1), 937 copy.deepcopy(self.section2), 938 np.copy(self.section3), 939 np.copy(self.section4), 940 np.copy(self.section5), 941 self.bitMapFlag.value, 942 ) 943 memo[id(self)] = new 944 945 new._msgnum = self._msgnum 946 new._deflist = np.copy(self._deflist) 947 new._coordlist = np.copy(self._coordlist) 948 new._auto_nans = self._auto_nans 949 950 # Handle data copy: 951 # If the original has an active unpacked array OR no backing file, pin a copy 952 arr = self._data_ref() if self._data_ref is not None else None 953 if arr is not None: 954 # We must assign to a strong reference or ensure setter accommodates pinned data 955 copied_arr = np.copy(arr) 956 new._data_pinned = copied_arr # Holds strong ref so weakref doesn't die 957 new._data_ref = weakref.ref(copied_arr) 958 else: 959 # Not yet decoded: clone the ondiskarray reference so it decodes on-demand 960 new._ondiskarray = copy.copy(self._ondiskarray) 961 new._data_pinned = None 962 new._data_ref = None 963 964 new.bitmap = None if self.bitmap is None else np.copy(self.bitmap) 965 return new 966 967 def __post_init__(self): 968 """Set some attributes after init.""" 969 self._auto_nans = _AUTO_NANS 970 self._coordlist = np.zeros((0), dtype=np.float32) 971 # self._data = None 972 self._data_ref = None 973 self._data_pinned = None 974 self._deflist = np.zeros((0), dtype=np.int64) 975 self._msgnum = -1 976 self._ondiskarray = None 977 self._orig_section5 = np.copy(self.section5) 978 self._signature = self._generate_signature() 979 try: 980 self._sha1_section3 = hashlib.sha1(self.section3).hexdigest() 981 except TypeError: 982 pass 983 self.bitMapFlag = templates.Grib2Metadata(self.bitMapFlag, table="6.0") 984 self.bitmap = None 985 986 @property 987 def _isNDFD(self): 988 """Check if GRIB2 message is from NWS NDFD""" 989 return np.all(self.section1[0:2] == [8, 65535]) 990 991 @property 992 def _isAerosol(self): 993 """Check if GRIB2 message contains aerosol data""" 994 is_aero_template = self.productDefinitionTemplateNumber.value in tables.AEROSOL_PDTNS 995 is_aero_param = (self.parameterCategory in {13, 20}) and (self.parameterNumber in tables.AEROSOL_PARAMS) 996 # Check table 4.205 aerosol presence 997 is_aero_type = self.parameterCategory == 205 and self.parameterNumber == 1 998 return is_aero_template or is_aero_param or is_aero_type 999 1000 @property 1001 def _isChemical(self): 1002 """Check if GRIB2 message contains chemical data""" 1003 is_chem_template = self.productDefinitionTemplateNumber.value in tables.CHEMICAL_PDTNS 1004 is_chem_param = self.parameterCategory == 20 1005 return is_chem_template or is_chem_param 1006 1007 @property 1008 def gdtn(self): 1009 """Return Grid Definition Template Number""" 1010 return self.section3[4] 1011 1012 @property 1013 def gdt(self): 1014 """Return Grid Definition Template.""" 1015 return self.gridDefinitionTemplate 1016 1017 @property 1018 def pdtn(self): 1019 """Return Product Definition Template Number.""" 1020 return self.section4[1] 1021 1022 @property 1023 def pdt(self): 1024 """Return Product Definition Template.""" 1025 return self.productDefinitionTemplate 1026 1027 @property 1028 def drtn(self): 1029 """Return Data Representation Template Number.""" 1030 return self.section5[1] 1031 1032 @property 1033 def drt(self): 1034 """Return Data Representation Template.""" 1035 return self.dataRepresentationTemplate 1036 1037 @property 1038 def pdy(self): 1039 """Return the PDY ('YYYYMMDD').""" 1040 return "".join([str(i) for i in self.section1[5:8]]) 1041 1042 @property 1043 def griddef(self): 1044 """Return a Grib2GridDef instance for a GRIB2 message.""" 1045 return Grib2GridDef.from_section3(self.section3) 1046 1047 @property 1048 def lats(self): 1049 """Return grid latitudes.""" 1050 return self.latlons()[0] 1051 1052 @property 1053 def lons(self): 1054 """Return grid longitudes.""" 1055 return self.latlons()[1] 1056 1057 @property 1058 def min(self): 1059 """Return minimum value of data.""" 1060 return np.nanmin(self.data) 1061 1062 @property 1063 def max(self): 1064 """Return maximum value of data.""" 1065 return np.nanmax(self.data) 1066 1067 @property 1068 def mean(self): 1069 """Return mean value of data.""" 1070 return np.nanmean(self.data) 1071 1072 @property 1073 def median(self): 1074 """Return median value of data.""" 1075 return np.nanmedian(self.data) 1076 1077 @property 1078 def shape(self): 1079 """Return shape of data.""" 1080 return self.griddef.shape 1081 1082 def __repr__(self): 1083 """ 1084 Return an unambiguous string representation of the object. 1085 1086 Returns 1087 ------- 1088 repr 1089 A string representation of the object, including information from 1090 sections 0, 1, 3, 4, 5, and 6. 1091 """ 1092 info = "" 1093 for sect in [0, 1, 3, 4, 5, 6]: 1094 for k, v in self.attrs_by_section(sect, values=True).items(): 1095 info += f"Section {sect}: {k} = {v}\n" 1096 return info 1097 1098 def __str__(self): 1099 """ 1100 Return a readable string representation of the object. 1101 1102 Returns 1103 ------- 1104 str 1105 A formatted string representation of the object, including 1106 selected attributes. 1107 """ 1108 pdtn = self.pdtn 1109 prefix = f"{self._msgnum}:d={self.refDate}:{self.shortName}:{self.fullName}" 1110 1111 if pdtn in {5, 9}: 1112 return f"{prefix} (%):{self.level}:{self.leadTime}:{self.duration}:{self.threshold} ({self.parameterUnits})" 1113 1114 if pdtn in {6, 10}: 1115 percentile = utils.percentile_string(self.percentileValue) 1116 return f"{prefix} ({self.units}):{self.level}:{self.leadTime}:{self.duration}:{percentile}" 1117 1118 if pdtn == 8: 1119 return f"{prefix} ({self.units}):{self.level}:{self.leadTime}:{self.duration} {self.statisticalProcess.definition}" 1120 1121 return f"{prefix} ({self.units}):{self.level}:{self.leadTime}" 1122 1123 def _generate_signature(self): 1124 """Generature SHA-1 hash string from GRIB2 integer sections.""" 1125 return hashlib.sha1( 1126 np.concatenate( 1127 ( 1128 self.section0, 1129 self.section1, 1130 self.section3, 1131 self.section4, 1132 self.section5, 1133 ) 1134 ) 1135 ).hexdigest() 1136 1137 def attrs_by_section(self, sect: int, values: bool = False): 1138 """ 1139 Provide a tuple of attribute names for the given GRIB2 section. 1140 1141 Parameters 1142 ---------- 1143 sect 1144 The GRIB2 section number. 1145 values 1146 Optional (default is `False`) argument to return attributes values. 1147 1148 Returns 1149 ------- 1150 attrs_by_section 1151 A list of attribute names or dict of name:value pairs if `values = 1152 True`. 1153 """ 1154 if sect in {0, 1, 6}: 1155 attrs = templates._section_attrs[sect] 1156 elif sect in {3, 4, 5}: 1157 1158 def _find_class_index(n): 1159 _key = {3: "Grid", 4: "Product", 5: "Data"} 1160 for i, c in enumerate(self.__class__.__mro__): 1161 if _key[n] in c.__name__: 1162 return i 1163 else: 1164 return [] 1165 1166 if sys.version_info.minor <= 8: 1167 attrs = templates._section_attrs[sect] + [a for a in dir(self.__class__.__mro__[_find_class_index(sect)]) if not a.startswith("_")] 1168 else: 1169 attrs = templates._section_attrs[sect] + self.__class__.__mro__[_find_class_index(sect)]._attrs() 1170 else: 1171 attrs = [] 1172 if values: 1173 return {k: getattr(self, k) for k in attrs} 1174 else: 1175 return attrs 1176 1177 def copy(self, deep: bool = True): 1178 """Returns a copy of this Grib2Message. 1179 1180 When `deep=True`, a copy is made of each of the GRIB2 section arrays and 1181 the data are unpacked from the source object and copied into the new 1182 object. Otherwise, a shallow copy of each array is performed and no data 1183 are copied. 1184 1185 Parameters 1186 ---------- 1187 deep : bool, default: True 1188 Whether each GRIB2 section array and data are copied onto 1189 the new object. Default is True. 1190 1191 Returns 1192 ------- 1193 object : Grib2Message 1194 New Grib2Message object. 1195 1196 .. versionadded:: 2.6.0 1197 """ 1198 return copy.deepcopy(self) if deep else copy.copy(self) 1199 1200 def pack(self): 1201 """ 1202 Pack GRIB2 section data into a binary message. 1203 1204 It is the user's responsibility to populate the GRIB2 section 1205 information with appropriate metadata. 1206 """ 1207 # Create beginning of packed binary message with section 0 and 1 data. 1208 self._sections = [] 1209 self._msg, self._pos = g2clib.grib2_create(self.indicatorSection[2:4], self.identificationSection) 1210 self._sections += [0, 1] 1211 1212 # Add section 2 if present. 1213 if isinstance(self.section2, bytes) and len(self.section2) > 0: 1214 self._msg, self._pos = g2clib.grib2_addlocal(self._msg, self.section2) 1215 self._sections.append(2) 1216 1217 # Add section 3. 1218 self.section3[1] = self.nx * self.ny 1219 self._msg, self._pos = g2clib.grib2_addgrid( 1220 self._msg, 1221 self.gridDefinitionSection, 1222 self.gridDefinitionTemplate, 1223 self._deflist, 1224 ) 1225 self._sections.append(3) 1226 1227 # Prepare data. 1228 try: 1229 field = np.copy(self.data) 1230 except ValueError: 1231 raise ValueError("Grib2Message object has no data, thus it cannot be packed.") 1232 if self.scanModeFlags is not None: 1233 if self.scanModeFlags[3]: 1234 fieldsave = field.astype("f") # Casting makes a copy 1235 field[1::2, :] = fieldsave[1::2, ::-1] 1236 fld = field.astype("f") 1237 1238 # Prepare bitmap, if necessary 1239 bitmapflag = self.bitMapFlag.value 1240 if bitmapflag == 0: 1241 if self.bitmap is not None: 1242 bmap = np.ravel(self.bitmap).astype(DEFAULT_NUMPY_INT) 1243 else: 1244 bmap = np.ravel(np.where(np.isnan(fld), 0, 1)).astype(DEFAULT_NUMPY_INT) 1245 else: 1246 bmap = None 1247 1248 # Prepare data for packing if nans are present 1249 fld = np.ravel(fld) 1250 if bitmapflag in {0, 254}: 1251 fld = np.where(np.isnan(fld), 0, fld) 1252 else: 1253 if np.isnan(fld).any(): 1254 if hasattr(self, "priMissingValue"): 1255 fld = np.where(np.isnan(fld), self.priMissingValue, fld) 1256 if hasattr(self, "_missvalmap"): 1257 if hasattr(self, "priMissingValue"): 1258 fld = np.where(self._missvalmap == 1, self.priMissingValue, fld) 1259 if hasattr(self, "secMissingValue"): 1260 fld = np.where(self._missvalmap == 2, self.secMissingValue, fld) 1261 1262 # Add sections 4, 5, 6, and 7. 1263 self._msg, self._pos = g2clib.grib2_addfield( 1264 self._msg, 1265 self.pdtn, 1266 self.productDefinitionTemplate, 1267 self._coordlist, 1268 self.drtn, 1269 self.dataRepresentationTemplate, 1270 fld, 1271 bitmapflag, 1272 bmap, 1273 ) 1274 self._sections.append(4) 1275 self._sections.append(5) 1276 self._sections.append(6) 1277 self._sections.append(7) 1278 1279 # Finalize GRIB2 message with section 8. 1280 self._msg, self._pos = g2clib.grib2_end(self._msg) 1281 self._sections.append(8) 1282 self.section0[-1] = len(self._msg) 1283 1284 @property 1285 def data(self) -> np.ndarray: 1286 """Access the unpacked data values.""" 1287 # 1. Check pinned strong reference first (for in-memory created messages) 1288 if self._data_pinned is not None: 1289 return self._data_pinned 1290 1291 # 2. Check weak reference (for file-backed messages) 1292 arr = self._data_ref() if self._data_ref is not None else None 1293 if arr is not None: 1294 return arr 1295 1296 # 3. If missing but ondiskarray exists, decode from disk on demand 1297 if self._ondiskarray is not None: 1298 arr = np.asarray(self._ondiskarray) 1299 self._data_ref = weakref.ref(arr) 1300 return arr 1301 1302 raise ValueError("Grib2Message object has no data.") 1303 1304 @data.setter 1305 def data(self, arr): 1306 if not isinstance(arr, np.ndarray): 1307 raise ValueError("Grib2Message data only supports numpy arrays") 1308 if self.nx == 0 and self.ny == 0: 1309 self.ny = arr.shape[0] 1310 self.nx = arr.shape[1] 1311 if arr.shape != (self.ny, self.nx): 1312 raise ValueError(f"Data shape mismatch: expected ({self.ny}, {self.nx}), got {arr.shape}") 1313 if not arr.flags["C_CONTIGUOUS"]: 1314 arr = np.ascontiguousarray(arr, dtype=np.float32) 1315 1316 # If this message is not tied to a file on disk, we MUST pin it strongly 1317 # so the data does not evaporate immediately. 1318 if self._ondiskarray is None: 1319 self._data_pinned = arr 1320 self._data_ref = None 1321 else: 1322 # If user explicitly sets custom data on a file-backed message, 1323 # pin it too because disk data no longer represents this message. 1324 self._data_pinned = arr 1325 self._data_ref = None 1326 1327 @property 1328 def _data(self): 1329 """Backward-compatible view of whether unpacked data is currently held.""" 1330 if self._data_pinned is not None: 1331 return self._data_pinned 1332 if self._data_ref is not None: 1333 return self._data_ref() 1334 return None 1335 1336 def flush_data(self): 1337 """ 1338 Flush the unpacked data values from the Grib2Message object. 1339 """ 1340 # Only allow flushing if we have a backing file to reload from 1341 if self._ondiskarray is not None: 1342 self._data_pinned = None 1343 self._data_ref = None 1344 else: 1345 # In-memory message with no backing file cannot be reloaded 1346 self._data_pinned = None 1347 self._data_ref = None 1348 1349 self.bitmap = None 1350 if hasattr(self, "_missvalmap"): 1351 del self._missvalmap 1352 1353 def __getitem__(self, item): 1354 return self.data[item] 1355 1356 def __setitem__(self, item): 1357 raise NotImplementedError("assignment of data not supported via setitem") 1358 1359 def latlons(self, *args, **kwrgs): 1360 """Alias for `grib2io.Grib2Message.grid` method.""" 1361 return self.grid(*args, **kwrgs) 1362 1363 def grid(self, unrotate: bool = True): 1364 """ 1365 Return lats,lons (in degrees) of grid. 1366 1367 Currently can handle reg. lat/lon,cglobal Gaussian, mercator, 1368 stereographic, lambert conformal, albers equal-area, space-view and 1369 azimuthal equidistant grids. 1370 1371 Parameters 1372 ---------- 1373 unrotate 1374 If `True` [DEFAULT], and grid is rotated lat/lon, then unrotate the 1375 grid, otherwise `False`, do not. 1376 1377 Returns 1378 ------- 1379 lats, lons : numpy.ndarray 1380 Returns two numpy.ndarrays with dtype=numpy.float32 of grid 1381 latitudes and longitudes in units of degrees. 1382 """ 1383 if self._sha1_section3 in _latlon_datastore.keys(): 1384 return ( 1385 _latlon_datastore[self._sha1_section3]["latitude"], 1386 _latlon_datastore[self._sha1_section3]["longitude"], 1387 ) 1388 gdtn = self.gridDefinitionTemplateNumber.value 1389 reggrid = self.gridDefinitionSection[2] == 0 # This means regular 2-d grid 1390 if gdtn == 0: 1391 # Regular lat/lon grid 1392 lon1, lat1 = self.longitudeFirstGridpoint, self.latitudeFirstGridpoint 1393 lon2, lat2 = self.longitudeLastGridpoint, self.latitudeLastGridpoint 1394 dlon = self.gridlengthXDirection 1395 if lon2 < lon1 and dlon < 0: 1396 lon1 = -lon1 1397 lats = np.linspace(lat1, lat2, self.ny) 1398 if reggrid: 1399 lons = np.linspace(lon1, lon2, self.nx) 1400 else: 1401 lons = np.linspace(lon1, lon2, self.ny * 2) 1402 lons, lats = np.meshgrid(lons, lats) # Make 2-d arrays. 1403 elif gdtn == 1: # Rotated Lat/Lon grid 1404 pj = pyproj.Proj(self.projParameters) 1405 lat1, lon1 = self.latitudeFirstGridpoint, self.longitudeFirstGridpoint 1406 lat2, lon2 = self.latitudeLastGridpoint, self.longitudeLastGridpoint 1407 if lon1 > 180.0: 1408 lon1 -= 360.0 1409 if lon2 > 180.0: 1410 lon2 -= 360.0 1411 lats = np.linspace(lat1, lat2, self.ny) 1412 lons = np.linspace(lon1, lon2, self.nx) 1413 lons, lats = np.meshgrid(lons, lats) # Make 2-d arrays. 1414 if unrotate: 1415 from grib2io.utils import rotated_grid 1416 1417 lats, lons = rotated_grid.unrotate( 1418 lats, 1419 lons, 1420 self.anglePoleRotation, 1421 self.latitudeSouthernPole, 1422 self.longitudeSouthernPole, 1423 ) 1424 elif gdtn == 40: # Gaussian grid (only works for global!) 1425 from grib2io.utils.gauss_grid import gaussian_latitudes 1426 1427 lon1, lat1 = self.longitudeFirstGridpoint, self.latitudeFirstGridpoint 1428 lon2, lat2 = self.longitudeLastGridpoint, self.latitudeLastGridpoint 1429 nlats = self.ny 1430 if not reggrid: # Reduced Gaussian grid. 1431 nlons = 2 * nlats 1432 dlon = 360.0 / nlons 1433 else: 1434 nlons = self.nx 1435 dlon = self.gridlengthXDirection 1436 lons = np.linspace(lon1, lon2, nlons) 1437 # Compute Gaussian lats (north to south) 1438 lats = gaussian_latitudes(nlats) 1439 if lat1 < lat2: # reverse them if necessary 1440 lats = lats[::-1] 1441 lons, lats = np.meshgrid(lons, lats) 1442 elif gdtn in {10, 20, 30, 31, 110}: 1443 # Mercator, Lambert Conformal, Stereographic, Albers Equal Area, 1444 # Azimuthal Equidistant 1445 dx, dy = self.gridlengthXDirection, self.gridlengthYDirection 1446 lon1, lat1 = self.longitudeFirstGridpoint, self.latitudeFirstGridpoint 1447 pj = pyproj.Proj(self.projParameters) 1448 llcrnrx, llcrnry = pj(lon1, lat1) 1449 x = llcrnrx + dx * np.arange(self.nx) 1450 y = llcrnry + dy * np.arange(self.ny) 1451 x, y = np.meshgrid(x, y) 1452 lons, lats = pj(x, y, inverse=True) 1453 elif gdtn == 90: 1454 # Satellite Projection 1455 dx = self.gridlengthXDirection 1456 dy = self.gridlengthYDirection 1457 pj = pyproj.Proj(self.projParameters) 1458 x = dx * np.indices((self.ny, self.nx), "f")[1, :, :] 1459 x -= 0.5 * x.max() 1460 y = dy * np.indices((self.ny, self.nx), "f")[0, :, :] 1461 y -= 0.5 * y.max() 1462 lons, lats = pj(x, y, inverse=True) 1463 # Set lons,lats to 1.e30 where undefined 1464 abslons = np.fabs(lons) 1465 abslats = np.fabs(lats) 1466 lons = np.where(abslons < 1.0e20, lons, 1.0e30) 1467 lats = np.where(abslats < 1.0e20, lats, 1.0e30) 1468 elif gdtn == 32769: 1469 # Special NCEP Grid, Rotated Lat/Lon, Arakawa E-Grid (Non-Staggered) 1470 from grib2io.utils import arakawa_rotated_grid 1471 1472 di, dj = 0.0, 0.0 1473 do_180 = False 1474 idir = 1 if self.scanModeFlags[0] == 0 else -1 1475 jdir = -1 if self.scanModeFlags[1] == 0 else 1 1476 0 if self.resolutionAndComponentFlags[4] == 0 else 1 1477 la1 = self.latitudeFirstGridpoint 1478 lo1 = self.longitudeFirstGridpoint 1479 clon = self.longitudeCenterGridpoint 1480 clat = self.latitudeCenterGridpoint 1481 lasp = clat - 90.0 1482 losp = clon 1483 llat, llon = arakawa_rotated_grid.ll2rot(la1, lo1, lasp, losp) 1484 la2, lo2 = arakawa_rotated_grid.rot2ll(-llat, -llon, lasp, losp) 1485 rlat = -llat 1486 rlon = -llon 1487 if self.nx == 1: 1488 di = 0.0 1489 elif idir == 1: 1490 ti = rlon 1491 while ti < llon: 1492 ti += 360.0 1493 di = (ti - llon) / float(self.nx - 1) 1494 else: 1495 ti = llon 1496 while ti < rlon: 1497 ti += 360.0 1498 di = (ti - rlon) / float(self.nx - 1) 1499 if self.ny == 1: 1500 dj = 0.0 1501 else: 1502 dj = (rlat - llat) / float(self.ny - 1) 1503 if dj < 0.0: 1504 dj = -dj 1505 if idir == 1: 1506 if llon > rlon: 1507 llon -= 360.0 1508 if llon < 0 and rlon > 0: 1509 do_180 = True 1510 else: 1511 if rlon > llon: 1512 rlon -= 360.0 1513 if rlon < 0 and llon > 0: 1514 do_180 = True 1515 xlat1d = llat + (np.arange(self.ny) * jdir * dj) 1516 xlon1d = llon + (np.arange(self.nx) * idir * di) 1517 xlons, xlats = np.meshgrid(xlon1d, xlat1d) 1518 rot2ll_vectorized = np.vectorize(arakawa_rotated_grid.rot2ll) 1519 lats, lons = rot2ll_vectorized(xlats, xlons, lasp, losp) 1520 if do_180: 1521 lons = np.where(lons > 180.0, lons - 360.0, lons) 1522 vector_rotation_angles_vectorized = np.vectorize(arakawa_rotated_grid.vector_rotation_angles) 1523 rots = vector_rotation_angles_vectorized(lats, lons, clat, losp, xlats) 1524 del xlat1d, xlon1d, xlats, xlons 1525 else: 1526 raise ValueError("Unsupported grid") 1527 1528 _latlon_datastore[self._sha1_section3] = dict(latitude=lats, longitude=lons) 1529 try: 1530 _latlon_datastore[self._sha1_section3]["vector_rotation_angles"] = rots 1531 except NameError: 1532 pass 1533 1534 return lats, lons 1535 1536 def map_keys(self): 1537 """ 1538 Unpack data grid replacing integer values with strings. 1539 1540 These types of fields are categorical or classifications where data 1541 values do not represent an observable or predictable physical quantity. 1542 An example of such a field would be [Dominant Precipitation Type - 1543 DPTYPE](https://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_doc/grib2_table4-201.shtml) 1544 1545 Returns 1546 ------- 1547 map_keys 1548 numpy.ndarray of string values per element. 1549 """ 1550 hold_auto_nans = _AUTO_NANS 1551 set_auto_nans(False) 1552 1553 if (np.all(self.section1[0:2] == [7, 14]) and self.shortName == "PWTHER") or (self._isNDFD and self.shortName in {"WX", "WWA"}): 1554 keys = utils.decode_wx_strings(self.section2) 1555 if hasattr(self, "priMissingValue") and self.priMissingValue not in [ 1556 None, 1557 0, 1558 ]: 1559 keys[int(self.priMissingValue)] = "Missing" 1560 if hasattr(self, "secMissingValue") and self.secMissingValue not in [ 1561 None, 1562 0, 1563 ]: 1564 keys[int(self.secMissingValue)] = "Missing" 1565 u, inv = np.unique(self.data, return_inverse=True) 1566 fld = np.array([keys[x] for x in u])[inv].reshape(self.data.shape) 1567 else: 1568 # For data whose units are defined in a code table (i.e. classification or mask) 1569 tblname = re.findall(r"\d\.\d+", self.units, re.IGNORECASE)[0] 1570 fld = self.data.astype(np.int32).astype(str) 1571 tbl = tables.get_table(tblname, expand=True) 1572 for val in np.unique(fld): 1573 fld = np.where(fld == val, tbl[val], fld) 1574 set_auto_nans(hold_auto_nans) 1575 return fld 1576 1577 def to_bytes(self, validate: bool = True): 1578 """ 1579 Return packed GRIB2 message in bytes format. 1580 1581 This will be useful for exporting data in non-file formats. For example, 1582 can be used to output grib data directly to S3 using the boto3 client 1583 without the need to write a temporary file to upload first. 1584 1585 Parameters 1586 ---------- 1587 validate: default=True 1588 If `True` (DEFAULT), validates first/last four bytes for proper 1589 formatting, else returns None. If `False`, message is output as is. 1590 1591 Returns 1592 ------- 1593 to_bytes 1594 Returns GRIB2 formatted message as bytes. 1595 """ 1596 if hasattr(self, "_msg"): 1597 if validate: 1598 if self.validate(): 1599 return self._msg 1600 else: 1601 return None 1602 else: 1603 return self._msg 1604 else: 1605 return None 1606 1607 def interpolate(self, method, grid_def_out, method_options=None, drtn=None, num_threads=1): 1608 """ 1609 Grib2Message Interpolator 1610 1611 Performs spatial interpolation via the [NCEPLIBS-ip 1612 library](https://github.com/NOAA-EMC/NCEPLIBS-ip). This interpolate 1613 method only supports scalar interpolation. If you need to perform 1614 vector interpolation, use the module-level `grib2io.interpolate` 1615 function. 1616 1617 Parameters 1618 ---------- 1619 method 1620 Interpolate method to use. This can either be an integer or string 1621 using the following mapping: 1622 1623 | Interpolate Scheme | Integer Value | 1624 | :---: | :---: | 1625 | 'bilinear' | 0 | 1626 | 'bicubic' | 1 | 1627 | 'neighbor' | 2 | 1628 | 'budget' | 3 | 1629 | 'spectral' | 4 | 1630 | 'neighbor-budget' | 6 | 1631 1632 grid_def_out : grib2io.Grib2GridDef 1633 Grib2GridDef object of the output grid. 1634 method_options : list of ints, optional 1635 Interpolation options. See the NCEPLIBS-ip documentation for 1636 more information on how these are used. 1637 drtn 1638 Data Representation Template to be used for the returned 1639 interpolated GRIB2 message. When `None`, the data representation 1640 template of the source GRIB2 message is used. Once again, it is the 1641 user's responsibility to properly set the Data Representation 1642 Template attributes. 1643 num_threads : int, optional 1644 Number of OpenMP threads to use for interpolation. The default 1645 value is 1. If NCEPLIBS-ip and grib2io's iplib extension module 1646 was not built with OpenMP, then this keyword argument and value 1647 will have no impact. 1648 1649 Returns 1650 ------- 1651 interpolate 1652 If interpolating to a grid, a new Grib2Message object is returned. 1653 The GRIB2 metadata of the new Grib2Message object is identical to 1654 the input except where required to be different because of the new 1655 grid specs and possibly a new data representation template. 1656 1657 If interpolating to station points, the interpolated data values are 1658 returned as a numpy.ndarray. 1659 """ 1660 section0 = self.section0 1661 section0[-1] = 0 1662 gds = [0, grid_def_out.npoints, 0, 255, grid_def_out.gdtn] 1663 section3 = np.concatenate((gds, grid_def_out.gdt)) 1664 drtn = self.drtn if drtn is None else drtn 1665 1666 msg = Grib2Message( 1667 section0, 1668 self.section1, 1669 self.section2, 1670 section3, 1671 self.section4, 1672 None, 1673 self.bitMapFlag.value, 1674 drtn=drtn, 1675 ) 1676 1677 msg._msgnum = -1 1678 msg._deflist = self._deflist 1679 msg._coordlist = self._coordlist 1680 if msg.typeOfValues == 0: 1681 pass 1682 elif msg.typeOfValues == 1: 1683 pass 1684 newdata = interpolate( 1685 self.data, 1686 method, 1687 Grib2GridDef.from_section3(self.section3), 1688 grid_def_out, 1689 method_options=method_options, 1690 num_threads=num_threads, 1691 ).reshape(msg.ny, msg.nx) 1692 msg.section5[0] = grid_def_out.npoints 1693 # msg._data = newdata.astype(np.float32) 1694 msg.data = newdata.astype(np.float32) 1695 return msg 1696 1697 def subset(self, lats, lons): 1698 """ 1699 Return a spatial subset. 1700 1701 Currently only supports regular grids of the following types: 1702 1703 | Grid Type | gdtn | 1704 | :---: | :---: | 1705 | Latitude/Longitude, Equidistant Cylindrical, or Plate Carree | 0 | 1706 | Rotated Latitude/Longitude | 1 | 1707 | Mercator | 10 | 1708 | Polar Stereographic | 20 | 1709 | Lambert Conformal | 30 | 1710 | Albers Equal-Area | 31 | 1711 | Gaussian Latitude/Longitude | 40 | 1712 | Equatorial Azimuthal Equidistant Projection | 110 | 1713 1714 Parameters 1715 ---------- 1716 lats 1717 List or tuple of latitudes. The minimum and maximum latitudes will 1718 be used to define the southern and northern boundaries. 1719 1720 The order of the latitudes is not important. The function will 1721 determine which is the minimum and maximum. 1722 1723 The latitudes should be in decimal degrees with 0.0 at the equator, 1724 positive values in the northern hemisphere increasing to 90, and 1725 negative values in the southern hemisphere decreasing to -90. 1726 lons 1727 List or tuple of longitudes. The minimum and maximum longitudes 1728 will be used to define the western and eastern boundaries. 1729 1730 The order of the longitudes is not important. The function will 1731 determine which is the minimum and maximum. 1732 1733 GRIB2 longitudes should be in decimal degrees with 0.0 at the prime 1734 meridian, positive values increasing eastward to 360. There are no 1735 negative GRIB2 longitudes. 1736 1737 The typical west longitudes that start at 0.0 at the prime meridian 1738 and decrease to -180 westward, are converted to GRIB2 longitudes by 1739 '360 - (absolute value of the west longitude)' where typical 1740 eastern longitudes are unchanged as GRIB2 longitudes. 1741 1742 Returns 1743 ------- 1744 subset 1745 A spatial subset of a GRIB2 message. 1746 """ 1747 if self.gdtn not in [0, 1, 10, 20, 30, 31, 40, 110]: 1748 raise ValueError( 1749 """ 1750 1751Subset only works for 1752 Latitude/Longitude, Equidistant Cylindrical, or Plate Carree (gdtn=0) 1753 Rotated Latitude/Longitude (gdtn=1) 1754 Mercator (gdtn=10) 1755 Polar Stereographic (gdtn=20) 1756 Lambert Conformal (gdtn=30) 1757 Albers Equal-Area (gdtn=31) 1758 Gaussian Latitude/Longitude (gdtn=40) 1759 Equatorial Azimuthal Equidistant Projection (gdtn=110) 1760 1761""" 1762 ) 1763 1764 if self.nx == 0 or self.ny == 0: 1765 raise ValueError( 1766 """ 1767 1768Subset only works for regular grids. 1769 1770""" 1771 ) 1772 1773 newmsg = Grib2Message( 1774 np.copy(self.section0), 1775 np.copy(self.section1), 1776 np.copy(self.section2), 1777 np.copy(self.section3), 1778 np.copy(self.section4), 1779 np.copy(self.section5), 1780 ) 1781 1782 msg_latitude, inlons = self.grid() 1783 1784 if lats is None: 1785 lats = (msg_latitude.flatten()[-1], msg_latitude.flatten()[0]) 1786 1787 lats = (min(lats), max(lats)) 1788 1789 if lons is None: 1790 lons = (inlons.flatten()[0], inlons.flatten()[-1]) 1791 1792 lons = (min(lons), max(lons)) 1793 1794 # Internally work in common lon data representation (0->360 positive eastward from 0) 1795 lons = np.mod(np.array(lons) + 360, 360) 1796 msg_longitude = np.mod(inlons + 360, 360) 1797 1798 spatial.verify_lat_lon_bounds(lats, lons) 1799 1800 snap_first_point = spatial.snap_to_nearest_cell_center(msg_latitude, msg_longitude, lats[0], lons[0]) 1801 snap_last_point = spatial.snap_to_nearest_cell_center(msg_latitude, msg_longitude, lats[1], lons[1]) 1802 lats = (snap_first_point[0], snap_last_point[0]) 1803 lons = (snap_first_point[1], snap_last_point[1]) 1804 1805 if len(msg_latitude.shape) == 2: 1806 mask_lats = np.any((msg_latitude >= lats[0]) & (msg_latitude <= lats[1]), axis=1) 1807 else: 1808 mask_lats = np.any((msg_latitude >= lats[0]) & (msg_latitude <= lats[1]), axis=0) 1809 mask_lons = np.any((msg_longitude >= lons[0]) & (msg_longitude <= lons[1]), axis=0) 1810 1811 newlats = msg_latitude[mask_lats, :][:, mask_lons] 1812 newlons = msg_longitude[mask_lats, :][:, mask_lons] 1813 1814 setattr(newmsg, "latitudeFirstGridpoint", newlats.flatten()[0]) 1815 setattr(newmsg, "longitudeFirstGridpoint", newlons.flatten()[0]) 1816 setattr(newmsg, "nx", np.count_nonzero(mask_lons)) 1817 setattr(newmsg, "ny", np.count_nonzero(mask_lats)) 1818 1819 # Set *LastGridpoint attributes even if only used for gdtn=[0, 1, 40]. 1820 # Even though unnecessary for some supported grid types, it won't 1821 # affect a grib2io message to set them. 1822 setattr(newmsg, "latitudeLastGridpoint", newlats.flatten()[-1]) 1823 setattr(newmsg, "longitudeLastGridpoint", newlons.flatten()[-1]) 1824 1825 setattr( 1826 newmsg, 1827 "data", 1828 self.data[mask_lats, :][:, mask_lons], 1829 ) 1830 1831 # Need to reset the '_sha1_section3' attribute to the hash of section 3 1832 # so the '.grid()' method ignores the cached lat/lon and instead 1833 # force the '.grid()' method to recompute the lat/lon values for the 1834 # new, subsetted grid. 1835 newmsg._sha1_section3 = hashlib.sha1(newmsg.section3).hexdigest() 1836 newmsg.grid() 1837 1838 return newmsg 1839 1840 def validate(self): 1841 """ 1842 Validate a complete GRIB2 message. 1843 1844 The g2c library does its own internal validation when g2_gribend() is called, but 1845 we will check in grib2io also. The validation checks if the first 4 bytes in 1846 self._msg is 'GRIB' and '7777' as the last 4 bytes and that the message length in 1847 section 0 equals the length of the packed message. 1848 1849 Returns 1850 ------- 1851 `True` if the packed GRIB2 message is complete and well-formed, `False` otherwise. 1852 """ 1853 valid = False 1854 if hasattr(self, "_msg"): 1855 if self._msg[0:4] + self._msg[-4:] == b"GRIB7777": 1856 if self.section0[-1] == len(self._msg): 1857 valid = True 1858 return valid
GRIB2 Message base class.
GRIB2 Section 1, Identification Section
GRIB2 Section 3, Grid Definition Section
Product Definition Template
1007 @property 1008 def gdtn(self): 1009 """Return Grid Definition Template Number""" 1010 return self.section3[4]
Return Grid Definition Template Number
1012 @property 1013 def gdt(self): 1014 """Return Grid Definition Template.""" 1015 return self.gridDefinitionTemplate
Return Grid Definition Template.
1017 @property 1018 def pdtn(self): 1019 """Return Product Definition Template Number.""" 1020 return self.section4[1]
Return Product Definition Template Number.
1022 @property 1023 def pdt(self): 1024 """Return Product Definition Template.""" 1025 return self.productDefinitionTemplate
Return Product Definition Template.
1027 @property 1028 def drtn(self): 1029 """Return Data Representation Template Number.""" 1030 return self.section5[1]
Return Data Representation Template Number.
1032 @property 1033 def drt(self): 1034 """Return Data Representation Template.""" 1035 return self.dataRepresentationTemplate
Return Data Representation Template.
1037 @property 1038 def pdy(self): 1039 """Return the PDY ('YYYYMMDD').""" 1040 return "".join([str(i) for i in self.section1[5:8]])
Return the PDY ('YYYYMMDD').
1042 @property 1043 def griddef(self): 1044 """Return a Grib2GridDef instance for a GRIB2 message.""" 1045 return Grib2GridDef.from_section3(self.section3)
Return a Grib2GridDef instance for a GRIB2 message.
1052 @property 1053 def lons(self): 1054 """Return grid longitudes.""" 1055 return self.latlons()[1]
Return grid longitudes.
1057 @property 1058 def min(self): 1059 """Return minimum value of data.""" 1060 return np.nanmin(self.data)
Return minimum value of data.
1062 @property 1063 def max(self): 1064 """Return maximum value of data.""" 1065 return np.nanmax(self.data)
Return maximum value of data.
1067 @property 1068 def mean(self): 1069 """Return mean value of data.""" 1070 return np.nanmean(self.data)
Return mean value of data.
1072 @property 1073 def median(self): 1074 """Return median value of data.""" 1075 return np.nanmedian(self.data)
Return median value of data.
1077 @property 1078 def shape(self): 1079 """Return shape of data.""" 1080 return self.griddef.shape
Return shape of data.
1137 def attrs_by_section(self, sect: int, values: bool = False): 1138 """ 1139 Provide a tuple of attribute names for the given GRIB2 section. 1140 1141 Parameters 1142 ---------- 1143 sect 1144 The GRIB2 section number. 1145 values 1146 Optional (default is `False`) argument to return attributes values. 1147 1148 Returns 1149 ------- 1150 attrs_by_section 1151 A list of attribute names or dict of name:value pairs if `values = 1152 True`. 1153 """ 1154 if sect in {0, 1, 6}: 1155 attrs = templates._section_attrs[sect] 1156 elif sect in {3, 4, 5}: 1157 1158 def _find_class_index(n): 1159 _key = {3: "Grid", 4: "Product", 5: "Data"} 1160 for i, c in enumerate(self.__class__.__mro__): 1161 if _key[n] in c.__name__: 1162 return i 1163 else: 1164 return [] 1165 1166 if sys.version_info.minor <= 8: 1167 attrs = templates._section_attrs[sect] + [a for a in dir(self.__class__.__mro__[_find_class_index(sect)]) if not a.startswith("_")] 1168 else: 1169 attrs = templates._section_attrs[sect] + self.__class__.__mro__[_find_class_index(sect)]._attrs() 1170 else: 1171 attrs = [] 1172 if values: 1173 return {k: getattr(self, k) for k in attrs} 1174 else: 1175 return attrs
Provide a tuple of attribute names for the given GRIB2 section.
Parameters
- sect: The GRIB2 section number.
- values: Optional (default is
False) argument to return attributes values.
Returns
- attrs_by_section: A list of attribute names or dict of name:value pairs if
values = True.
1177 def copy(self, deep: bool = True): 1178 """Returns a copy of this Grib2Message. 1179 1180 When `deep=True`, a copy is made of each of the GRIB2 section arrays and 1181 the data are unpacked from the source object and copied into the new 1182 object. Otherwise, a shallow copy of each array is performed and no data 1183 are copied. 1184 1185 Parameters 1186 ---------- 1187 deep : bool, default: True 1188 Whether each GRIB2 section array and data are copied onto 1189 the new object. Default is True. 1190 1191 Returns 1192 ------- 1193 object : Grib2Message 1194 New Grib2Message object. 1195 1196 .. versionadded:: 2.6.0 1197 """ 1198 return copy.deepcopy(self) if deep else copy.copy(self)
Returns a copy of this Grib2Message.
When deep=True, a copy is made of each of the GRIB2 section arrays and
the data are unpacked from the source object and copied into the new
object. Otherwise, a shallow copy of each array is performed and no data
are copied.
Parameters
- deep : bool, default (True): Whether each GRIB2 section array and data are copied onto the new object. Default is True.
Returns
object (Grib2Message): New Grib2Message object.
New in version 2.6.0.
1200 def pack(self): 1201 """ 1202 Pack GRIB2 section data into a binary message. 1203 1204 It is the user's responsibility to populate the GRIB2 section 1205 information with appropriate metadata. 1206 """ 1207 # Create beginning of packed binary message with section 0 and 1 data. 1208 self._sections = [] 1209 self._msg, self._pos = g2clib.grib2_create(self.indicatorSection[2:4], self.identificationSection) 1210 self._sections += [0, 1] 1211 1212 # Add section 2 if present. 1213 if isinstance(self.section2, bytes) and len(self.section2) > 0: 1214 self._msg, self._pos = g2clib.grib2_addlocal(self._msg, self.section2) 1215 self._sections.append(2) 1216 1217 # Add section 3. 1218 self.section3[1] = self.nx * self.ny 1219 self._msg, self._pos = g2clib.grib2_addgrid( 1220 self._msg, 1221 self.gridDefinitionSection, 1222 self.gridDefinitionTemplate, 1223 self._deflist, 1224 ) 1225 self._sections.append(3) 1226 1227 # Prepare data. 1228 try: 1229 field = np.copy(self.data) 1230 except ValueError: 1231 raise ValueError("Grib2Message object has no data, thus it cannot be packed.") 1232 if self.scanModeFlags is not None: 1233 if self.scanModeFlags[3]: 1234 fieldsave = field.astype("f") # Casting makes a copy 1235 field[1::2, :] = fieldsave[1::2, ::-1] 1236 fld = field.astype("f") 1237 1238 # Prepare bitmap, if necessary 1239 bitmapflag = self.bitMapFlag.value 1240 if bitmapflag == 0: 1241 if self.bitmap is not None: 1242 bmap = np.ravel(self.bitmap).astype(DEFAULT_NUMPY_INT) 1243 else: 1244 bmap = np.ravel(np.where(np.isnan(fld), 0, 1)).astype(DEFAULT_NUMPY_INT) 1245 else: 1246 bmap = None 1247 1248 # Prepare data for packing if nans are present 1249 fld = np.ravel(fld) 1250 if bitmapflag in {0, 254}: 1251 fld = np.where(np.isnan(fld), 0, fld) 1252 else: 1253 if np.isnan(fld).any(): 1254 if hasattr(self, "priMissingValue"): 1255 fld = np.where(np.isnan(fld), self.priMissingValue, fld) 1256 if hasattr(self, "_missvalmap"): 1257 if hasattr(self, "priMissingValue"): 1258 fld = np.where(self._missvalmap == 1, self.priMissingValue, fld) 1259 if hasattr(self, "secMissingValue"): 1260 fld = np.where(self._missvalmap == 2, self.secMissingValue, fld) 1261 1262 # Add sections 4, 5, 6, and 7. 1263 self._msg, self._pos = g2clib.grib2_addfield( 1264 self._msg, 1265 self.pdtn, 1266 self.productDefinitionTemplate, 1267 self._coordlist, 1268 self.drtn, 1269 self.dataRepresentationTemplate, 1270 fld, 1271 bitmapflag, 1272 bmap, 1273 ) 1274 self._sections.append(4) 1275 self._sections.append(5) 1276 self._sections.append(6) 1277 self._sections.append(7) 1278 1279 # Finalize GRIB2 message with section 8. 1280 self._msg, self._pos = g2clib.grib2_end(self._msg) 1281 self._sections.append(8) 1282 self.section0[-1] = len(self._msg)
Pack GRIB2 section data into a binary message.
It is the user's responsibility to populate the GRIB2 section information with appropriate metadata.
1284 @property 1285 def data(self) -> np.ndarray: 1286 """Access the unpacked data values.""" 1287 # 1. Check pinned strong reference first (for in-memory created messages) 1288 if self._data_pinned is not None: 1289 return self._data_pinned 1290 1291 # 2. Check weak reference (for file-backed messages) 1292 arr = self._data_ref() if self._data_ref is not None else None 1293 if arr is not None: 1294 return arr 1295 1296 # 3. If missing but ondiskarray exists, decode from disk on demand 1297 if self._ondiskarray is not None: 1298 arr = np.asarray(self._ondiskarray) 1299 self._data_ref = weakref.ref(arr) 1300 return arr 1301 1302 raise ValueError("Grib2Message object has no data.")
Access the unpacked data values.
1336 def flush_data(self): 1337 """ 1338 Flush the unpacked data values from the Grib2Message object. 1339 """ 1340 # Only allow flushing if we have a backing file to reload from 1341 if self._ondiskarray is not None: 1342 self._data_pinned = None 1343 self._data_ref = None 1344 else: 1345 # In-memory message with no backing file cannot be reloaded 1346 self._data_pinned = None 1347 self._data_ref = None 1348 1349 self.bitmap = None 1350 if hasattr(self, "_missvalmap"): 1351 del self._missvalmap
Flush the unpacked data values from the Grib2Message object.
1359 def latlons(self, *args, **kwrgs): 1360 """Alias for `grib2io.Grib2Message.grid` method.""" 1361 return self.grid(*args, **kwrgs)
Alias for grib2io.Grib2Message.grid method.
1363 def grid(self, unrotate: bool = True): 1364 """ 1365 Return lats,lons (in degrees) of grid. 1366 1367 Currently can handle reg. lat/lon,cglobal Gaussian, mercator, 1368 stereographic, lambert conformal, albers equal-area, space-view and 1369 azimuthal equidistant grids. 1370 1371 Parameters 1372 ---------- 1373 unrotate 1374 If `True` [DEFAULT], and grid is rotated lat/lon, then unrotate the 1375 grid, otherwise `False`, do not. 1376 1377 Returns 1378 ------- 1379 lats, lons : numpy.ndarray 1380 Returns two numpy.ndarrays with dtype=numpy.float32 of grid 1381 latitudes and longitudes in units of degrees. 1382 """ 1383 if self._sha1_section3 in _latlon_datastore.keys(): 1384 return ( 1385 _latlon_datastore[self._sha1_section3]["latitude"], 1386 _latlon_datastore[self._sha1_section3]["longitude"], 1387 ) 1388 gdtn = self.gridDefinitionTemplateNumber.value 1389 reggrid = self.gridDefinitionSection[2] == 0 # This means regular 2-d grid 1390 if gdtn == 0: 1391 # Regular lat/lon grid 1392 lon1, lat1 = self.longitudeFirstGridpoint, self.latitudeFirstGridpoint 1393 lon2, lat2 = self.longitudeLastGridpoint, self.latitudeLastGridpoint 1394 dlon = self.gridlengthXDirection 1395 if lon2 < lon1 and dlon < 0: 1396 lon1 = -lon1 1397 lats = np.linspace(lat1, lat2, self.ny) 1398 if reggrid: 1399 lons = np.linspace(lon1, lon2, self.nx) 1400 else: 1401 lons = np.linspace(lon1, lon2, self.ny * 2) 1402 lons, lats = np.meshgrid(lons, lats) # Make 2-d arrays. 1403 elif gdtn == 1: # Rotated Lat/Lon grid 1404 pj = pyproj.Proj(self.projParameters) 1405 lat1, lon1 = self.latitudeFirstGridpoint, self.longitudeFirstGridpoint 1406 lat2, lon2 = self.latitudeLastGridpoint, self.longitudeLastGridpoint 1407 if lon1 > 180.0: 1408 lon1 -= 360.0 1409 if lon2 > 180.0: 1410 lon2 -= 360.0 1411 lats = np.linspace(lat1, lat2, self.ny) 1412 lons = np.linspace(lon1, lon2, self.nx) 1413 lons, lats = np.meshgrid(lons, lats) # Make 2-d arrays. 1414 if unrotate: 1415 from grib2io.utils import rotated_grid 1416 1417 lats, lons = rotated_grid.unrotate( 1418 lats, 1419 lons, 1420 self.anglePoleRotation, 1421 self.latitudeSouthernPole, 1422 self.longitudeSouthernPole, 1423 ) 1424 elif gdtn == 40: # Gaussian grid (only works for global!) 1425 from grib2io.utils.gauss_grid import gaussian_latitudes 1426 1427 lon1, lat1 = self.longitudeFirstGridpoint, self.latitudeFirstGridpoint 1428 lon2, lat2 = self.longitudeLastGridpoint, self.latitudeLastGridpoint 1429 nlats = self.ny 1430 if not reggrid: # Reduced Gaussian grid. 1431 nlons = 2 * nlats 1432 dlon = 360.0 / nlons 1433 else: 1434 nlons = self.nx 1435 dlon = self.gridlengthXDirection 1436 lons = np.linspace(lon1, lon2, nlons) 1437 # Compute Gaussian lats (north to south) 1438 lats = gaussian_latitudes(nlats) 1439 if lat1 < lat2: # reverse them if necessary 1440 lats = lats[::-1] 1441 lons, lats = np.meshgrid(lons, lats) 1442 elif gdtn in {10, 20, 30, 31, 110}: 1443 # Mercator, Lambert Conformal, Stereographic, Albers Equal Area, 1444 # Azimuthal Equidistant 1445 dx, dy = self.gridlengthXDirection, self.gridlengthYDirection 1446 lon1, lat1 = self.longitudeFirstGridpoint, self.latitudeFirstGridpoint 1447 pj = pyproj.Proj(self.projParameters) 1448 llcrnrx, llcrnry = pj(lon1, lat1) 1449 x = llcrnrx + dx * np.arange(self.nx) 1450 y = llcrnry + dy * np.arange(self.ny) 1451 x, y = np.meshgrid(x, y) 1452 lons, lats = pj(x, y, inverse=True) 1453 elif gdtn == 90: 1454 # Satellite Projection 1455 dx = self.gridlengthXDirection 1456 dy = self.gridlengthYDirection 1457 pj = pyproj.Proj(self.projParameters) 1458 x = dx * np.indices((self.ny, self.nx), "f")[1, :, :] 1459 x -= 0.5 * x.max() 1460 y = dy * np.indices((self.ny, self.nx), "f")[0, :, :] 1461 y -= 0.5 * y.max() 1462 lons, lats = pj(x, y, inverse=True) 1463 # Set lons,lats to 1.e30 where undefined 1464 abslons = np.fabs(lons) 1465 abslats = np.fabs(lats) 1466 lons = np.where(abslons < 1.0e20, lons, 1.0e30) 1467 lats = np.where(abslats < 1.0e20, lats, 1.0e30) 1468 elif gdtn == 32769: 1469 # Special NCEP Grid, Rotated Lat/Lon, Arakawa E-Grid (Non-Staggered) 1470 from grib2io.utils import arakawa_rotated_grid 1471 1472 di, dj = 0.0, 0.0 1473 do_180 = False 1474 idir = 1 if self.scanModeFlags[0] == 0 else -1 1475 jdir = -1 if self.scanModeFlags[1] == 0 else 1 1476 0 if self.resolutionAndComponentFlags[4] == 0 else 1 1477 la1 = self.latitudeFirstGridpoint 1478 lo1 = self.longitudeFirstGridpoint 1479 clon = self.longitudeCenterGridpoint 1480 clat = self.latitudeCenterGridpoint 1481 lasp = clat - 90.0 1482 losp = clon 1483 llat, llon = arakawa_rotated_grid.ll2rot(la1, lo1, lasp, losp) 1484 la2, lo2 = arakawa_rotated_grid.rot2ll(-llat, -llon, lasp, losp) 1485 rlat = -llat 1486 rlon = -llon 1487 if self.nx == 1: 1488 di = 0.0 1489 elif idir == 1: 1490 ti = rlon 1491 while ti < llon: 1492 ti += 360.0 1493 di = (ti - llon) / float(self.nx - 1) 1494 else: 1495 ti = llon 1496 while ti < rlon: 1497 ti += 360.0 1498 di = (ti - rlon) / float(self.nx - 1) 1499 if self.ny == 1: 1500 dj = 0.0 1501 else: 1502 dj = (rlat - llat) / float(self.ny - 1) 1503 if dj < 0.0: 1504 dj = -dj 1505 if idir == 1: 1506 if llon > rlon: 1507 llon -= 360.0 1508 if llon < 0 and rlon > 0: 1509 do_180 = True 1510 else: 1511 if rlon > llon: 1512 rlon -= 360.0 1513 if rlon < 0 and llon > 0: 1514 do_180 = True 1515 xlat1d = llat + (np.arange(self.ny) * jdir * dj) 1516 xlon1d = llon + (np.arange(self.nx) * idir * di) 1517 xlons, xlats = np.meshgrid(xlon1d, xlat1d) 1518 rot2ll_vectorized = np.vectorize(arakawa_rotated_grid.rot2ll) 1519 lats, lons = rot2ll_vectorized(xlats, xlons, lasp, losp) 1520 if do_180: 1521 lons = np.where(lons > 180.0, lons - 360.0, lons) 1522 vector_rotation_angles_vectorized = np.vectorize(arakawa_rotated_grid.vector_rotation_angles) 1523 rots = vector_rotation_angles_vectorized(lats, lons, clat, losp, xlats) 1524 del xlat1d, xlon1d, xlats, xlons 1525 else: 1526 raise ValueError("Unsupported grid") 1527 1528 _latlon_datastore[self._sha1_section3] = dict(latitude=lats, longitude=lons) 1529 try: 1530 _latlon_datastore[self._sha1_section3]["vector_rotation_angles"] = rots 1531 except NameError: 1532 pass 1533 1534 return lats, lons
Return lats,lons (in degrees) of grid.
Currently can handle reg. lat/lon,cglobal Gaussian, mercator, stereographic, lambert conformal, albers equal-area, space-view and azimuthal equidistant grids.
Parameters
- unrotate: If
True[DEFAULT], and grid is rotated lat/lon, then unrotate the grid, otherwiseFalse, do not.
Returns
- lats, lons (numpy.ndarray): Returns two numpy.ndarrays with dtype=numpy.float32 of grid latitudes and longitudes in units of degrees.
1536 def map_keys(self): 1537 """ 1538 Unpack data grid replacing integer values with strings. 1539 1540 These types of fields are categorical or classifications where data 1541 values do not represent an observable or predictable physical quantity. 1542 An example of such a field would be [Dominant Precipitation Type - 1543 DPTYPE](https://www.nco.ncep.noaa.gov/pmb/docs/grib2/grib2_doc/grib2_table4-201.shtml) 1544 1545 Returns 1546 ------- 1547 map_keys 1548 numpy.ndarray of string values per element. 1549 """ 1550 hold_auto_nans = _AUTO_NANS 1551 set_auto_nans(False) 1552 1553 if (np.all(self.section1[0:2] == [7, 14]) and self.shortName == "PWTHER") or (self._isNDFD and self.shortName in {"WX", "WWA"}): 1554 keys = utils.decode_wx_strings(self.section2) 1555 if hasattr(self, "priMissingValue") and self.priMissingValue not in [ 1556 None, 1557 0, 1558 ]: 1559 keys[int(self.priMissingValue)] = "Missing" 1560 if hasattr(self, "secMissingValue") and self.secMissingValue not in [ 1561 None, 1562 0, 1563 ]: 1564 keys[int(self.secMissingValue)] = "Missing" 1565 u, inv = np.unique(self.data, return_inverse=True) 1566 fld = np.array([keys[x] for x in u])[inv].reshape(self.data.shape) 1567 else: 1568 # For data whose units are defined in a code table (i.e. classification or mask) 1569 tblname = re.findall(r"\d\.\d+", self.units, re.IGNORECASE)[0] 1570 fld = self.data.astype(np.int32).astype(str) 1571 tbl = tables.get_table(tblname, expand=True) 1572 for val in np.unique(fld): 1573 fld = np.where(fld == val, tbl[val], fld) 1574 set_auto_nans(hold_auto_nans) 1575 return fld
Unpack data grid replacing integer values with strings.
These types of fields are categorical or classifications where data values do not represent an observable or predictable physical quantity. An example of such a field would be Dominant Precipitation Type - DPTYPE
Returns
- map_keys: numpy.ndarray of string values per element.
1577 def to_bytes(self, validate: bool = True): 1578 """ 1579 Return packed GRIB2 message in bytes format. 1580 1581 This will be useful for exporting data in non-file formats. For example, 1582 can be used to output grib data directly to S3 using the boto3 client 1583 without the need to write a temporary file to upload first. 1584 1585 Parameters 1586 ---------- 1587 validate: default=True 1588 If `True` (DEFAULT), validates first/last four bytes for proper 1589 formatting, else returns None. If `False`, message is output as is. 1590 1591 Returns 1592 ------- 1593 to_bytes 1594 Returns GRIB2 formatted message as bytes. 1595 """ 1596 if hasattr(self, "_msg"): 1597 if validate: 1598 if self.validate(): 1599 return self._msg 1600 else: 1601 return None 1602 else: 1603 return self._msg 1604 else: 1605 return None
Return packed GRIB2 message in bytes format.
This will be useful for exporting data in non-file formats. For example, can be used to output grib data directly to S3 using the boto3 client without the need to write a temporary file to upload first.
Parameters
- validate (default=True):
If
True(DEFAULT), validates first/last four bytes for proper formatting, else returns None. IfFalse, message is output as is.
Returns
- to_bytes: Returns GRIB2 formatted message as bytes.
1607 def interpolate(self, method, grid_def_out, method_options=None, drtn=None, num_threads=1): 1608 """ 1609 Grib2Message Interpolator 1610 1611 Performs spatial interpolation via the [NCEPLIBS-ip 1612 library](https://github.com/NOAA-EMC/NCEPLIBS-ip). This interpolate 1613 method only supports scalar interpolation. If you need to perform 1614 vector interpolation, use the module-level `grib2io.interpolate` 1615 function. 1616 1617 Parameters 1618 ---------- 1619 method 1620 Interpolate method to use. This can either be an integer or string 1621 using the following mapping: 1622 1623 | Interpolate Scheme | Integer Value | 1624 | :---: | :---: | 1625 | 'bilinear' | 0 | 1626 | 'bicubic' | 1 | 1627 | 'neighbor' | 2 | 1628 | 'budget' | 3 | 1629 | 'spectral' | 4 | 1630 | 'neighbor-budget' | 6 | 1631 1632 grid_def_out : grib2io.Grib2GridDef 1633 Grib2GridDef object of the output grid. 1634 method_options : list of ints, optional 1635 Interpolation options. See the NCEPLIBS-ip documentation for 1636 more information on how these are used. 1637 drtn 1638 Data Representation Template to be used for the returned 1639 interpolated GRIB2 message. When `None`, the data representation 1640 template of the source GRIB2 message is used. Once again, it is the 1641 user's responsibility to properly set the Data Representation 1642 Template attributes. 1643 num_threads : int, optional 1644 Number of OpenMP threads to use for interpolation. The default 1645 value is 1. If NCEPLIBS-ip and grib2io's iplib extension module 1646 was not built with OpenMP, then this keyword argument and value 1647 will have no impact. 1648 1649 Returns 1650 ------- 1651 interpolate 1652 If interpolating to a grid, a new Grib2Message object is returned. 1653 The GRIB2 metadata of the new Grib2Message object is identical to 1654 the input except where required to be different because of the new 1655 grid specs and possibly a new data representation template. 1656 1657 If interpolating to station points, the interpolated data values are 1658 returned as a numpy.ndarray. 1659 """ 1660 section0 = self.section0 1661 section0[-1] = 0 1662 gds = [0, grid_def_out.npoints, 0, 255, grid_def_out.gdtn] 1663 section3 = np.concatenate((gds, grid_def_out.gdt)) 1664 drtn = self.drtn if drtn is None else drtn 1665 1666 msg = Grib2Message( 1667 section0, 1668 self.section1, 1669 self.section2, 1670 section3, 1671 self.section4, 1672 None, 1673 self.bitMapFlag.value, 1674 drtn=drtn, 1675 ) 1676 1677 msg._msgnum = -1 1678 msg._deflist = self._deflist 1679 msg._coordlist = self._coordlist 1680 if msg.typeOfValues == 0: 1681 pass 1682 elif msg.typeOfValues == 1: 1683 pass 1684 newdata = interpolate( 1685 self.data, 1686 method, 1687 Grib2GridDef.from_section3(self.section3), 1688 grid_def_out, 1689 method_options=method_options, 1690 num_threads=num_threads, 1691 ).reshape(msg.ny, msg.nx) 1692 msg.section5[0] = grid_def_out.npoints 1693 # msg._data = newdata.astype(np.float32) 1694 msg.data = newdata.astype(np.float32) 1695 return msg
Grib2Message Interpolator
Performs spatial interpolation via the NCEPLIBS-ip
library. This interpolate
method only supports scalar interpolation. If you need to perform
vector interpolation, use the module-level grib2io.interpolate
function.
Parameters
- method: Interpolate method to use. This can either be an integer or string using the following mapping:
| Interpolate Scheme | Integer Value |
|---|---|
| 'bilinear' | 0 |
| 'bicubic' | 1 |
| 'neighbor' | 2 |
| 'budget' | 3 |
| 'spectral' | 4 |
| 'neighbor-budget' | 6 |
- grid_def_out (grib2io.Grib2GridDef): Grib2GridDef object of the output grid.
- method_options (list of ints, optional): Interpolation options. See the NCEPLIBS-ip documentation for more information on how these are used.
- drtn: Data Representation Template to be used for the returned
interpolated GRIB2 message. When
None, the data representation template of the source GRIB2 message is used. Once again, it is the user's responsibility to properly set the Data Representation Template attributes. - num_threads (int, optional): Number of OpenMP threads to use for interpolation. The default value is 1. If NCEPLIBS-ip and grib2io's iplib extension module was not built with OpenMP, then this keyword argument and value will have no impact.
Returns
- interpolate: If interpolating to a grid, a new Grib2Message object is returned. The GRIB2 metadata of the new Grib2Message object is identical to the input except where required to be different because of the new grid specs and possibly a new data representation template.
If interpolating to station points, the interpolated data values are returned as a numpy.ndarray.
1697 def subset(self, lats, lons): 1698 """ 1699 Return a spatial subset. 1700 1701 Currently only supports regular grids of the following types: 1702 1703 | Grid Type | gdtn | 1704 | :---: | :---: | 1705 | Latitude/Longitude, Equidistant Cylindrical, or Plate Carree | 0 | 1706 | Rotated Latitude/Longitude | 1 | 1707 | Mercator | 10 | 1708 | Polar Stereographic | 20 | 1709 | Lambert Conformal | 30 | 1710 | Albers Equal-Area | 31 | 1711 | Gaussian Latitude/Longitude | 40 | 1712 | Equatorial Azimuthal Equidistant Projection | 110 | 1713 1714 Parameters 1715 ---------- 1716 lats 1717 List or tuple of latitudes. The minimum and maximum latitudes will 1718 be used to define the southern and northern boundaries. 1719 1720 The order of the latitudes is not important. The function will 1721 determine which is the minimum and maximum. 1722 1723 The latitudes should be in decimal degrees with 0.0 at the equator, 1724 positive values in the northern hemisphere increasing to 90, and 1725 negative values in the southern hemisphere decreasing to -90. 1726 lons 1727 List or tuple of longitudes. The minimum and maximum longitudes 1728 will be used to define the western and eastern boundaries. 1729 1730 The order of the longitudes is not important. The function will 1731 determine which is the minimum and maximum. 1732 1733 GRIB2 longitudes should be in decimal degrees with 0.0 at the prime 1734 meridian, positive values increasing eastward to 360. There are no 1735 negative GRIB2 longitudes. 1736 1737 The typical west longitudes that start at 0.0 at the prime meridian 1738 and decrease to -180 westward, are converted to GRIB2 longitudes by 1739 '360 - (absolute value of the west longitude)' where typical 1740 eastern longitudes are unchanged as GRIB2 longitudes. 1741 1742 Returns 1743 ------- 1744 subset 1745 A spatial subset of a GRIB2 message. 1746 """ 1747 if self.gdtn not in [0, 1, 10, 20, 30, 31, 40, 110]: 1748 raise ValueError( 1749 """ 1750 1751Subset only works for 1752 Latitude/Longitude, Equidistant Cylindrical, or Plate Carree (gdtn=0) 1753 Rotated Latitude/Longitude (gdtn=1) 1754 Mercator (gdtn=10) 1755 Polar Stereographic (gdtn=20) 1756 Lambert Conformal (gdtn=30) 1757 Albers Equal-Area (gdtn=31) 1758 Gaussian Latitude/Longitude (gdtn=40) 1759 Equatorial Azimuthal Equidistant Projection (gdtn=110) 1760 1761""" 1762 ) 1763 1764 if self.nx == 0 or self.ny == 0: 1765 raise ValueError( 1766 """ 1767 1768Subset only works for regular grids. 1769 1770""" 1771 ) 1772 1773 newmsg = Grib2Message( 1774 np.copy(self.section0), 1775 np.copy(self.section1), 1776 np.copy(self.section2), 1777 np.copy(self.section3), 1778 np.copy(self.section4), 1779 np.copy(self.section5), 1780 ) 1781 1782 msg_latitude, inlons = self.grid() 1783 1784 if lats is None: 1785 lats = (msg_latitude.flatten()[-1], msg_latitude.flatten()[0]) 1786 1787 lats = (min(lats), max(lats)) 1788 1789 if lons is None: 1790 lons = (inlons.flatten()[0], inlons.flatten()[-1]) 1791 1792 lons = (min(lons), max(lons)) 1793 1794 # Internally work in common lon data representation (0->360 positive eastward from 0) 1795 lons = np.mod(np.array(lons) + 360, 360) 1796 msg_longitude = np.mod(inlons + 360, 360) 1797 1798 spatial.verify_lat_lon_bounds(lats, lons) 1799 1800 snap_first_point = spatial.snap_to_nearest_cell_center(msg_latitude, msg_longitude, lats[0], lons[0]) 1801 snap_last_point = spatial.snap_to_nearest_cell_center(msg_latitude, msg_longitude, lats[1], lons[1]) 1802 lats = (snap_first_point[0], snap_last_point[0]) 1803 lons = (snap_first_point[1], snap_last_point[1]) 1804 1805 if len(msg_latitude.shape) == 2: 1806 mask_lats = np.any((msg_latitude >= lats[0]) & (msg_latitude <= lats[1]), axis=1) 1807 else: 1808 mask_lats = np.any((msg_latitude >= lats[0]) & (msg_latitude <= lats[1]), axis=0) 1809 mask_lons = np.any((msg_longitude >= lons[0]) & (msg_longitude <= lons[1]), axis=0) 1810 1811 newlats = msg_latitude[mask_lats, :][:, mask_lons] 1812 newlons = msg_longitude[mask_lats, :][:, mask_lons] 1813 1814 setattr(newmsg, "latitudeFirstGridpoint", newlats.flatten()[0]) 1815 setattr(newmsg, "longitudeFirstGridpoint", newlons.flatten()[0]) 1816 setattr(newmsg, "nx", np.count_nonzero(mask_lons)) 1817 setattr(newmsg, "ny", np.count_nonzero(mask_lats)) 1818 1819 # Set *LastGridpoint attributes even if only used for gdtn=[0, 1, 40]. 1820 # Even though unnecessary for some supported grid types, it won't 1821 # affect a grib2io message to set them. 1822 setattr(newmsg, "latitudeLastGridpoint", newlats.flatten()[-1]) 1823 setattr(newmsg, "longitudeLastGridpoint", newlons.flatten()[-1]) 1824 1825 setattr( 1826 newmsg, 1827 "data", 1828 self.data[mask_lats, :][:, mask_lons], 1829 ) 1830 1831 # Need to reset the '_sha1_section3' attribute to the hash of section 3 1832 # so the '.grid()' method ignores the cached lat/lon and instead 1833 # force the '.grid()' method to recompute the lat/lon values for the 1834 # new, subsetted grid. 1835 newmsg._sha1_section3 = hashlib.sha1(newmsg.section3).hexdigest() 1836 newmsg.grid() 1837 1838 return newmsg
Return a spatial subset.
Currently only supports regular grids of the following types:
| Grid Type | gdtn |
|---|---|
| Latitude/Longitude, Equidistant Cylindrical, or Plate Carree | 0 |
| Rotated Latitude/Longitude | 1 |
| Mercator | 10 |
| Polar Stereographic | 20 |
| Lambert Conformal | 30 |
| Albers Equal-Area | 31 |
| Gaussian Latitude/Longitude | 40 |
| Equatorial Azimuthal Equidistant Projection | 110 |
Parameters
- lats: List or tuple of latitudes. The minimum and maximum latitudes will be used to define the southern and northern boundaries.
The order of the latitudes is not important. The function will determine which is the minimum and maximum.
The latitudes should be in decimal degrees with 0.0 at the equator, positive values in the northern hemisphere increasing to 90, and negative values in the southern hemisphere decreasing to -90.
- lons: List or tuple of longitudes. The minimum and maximum longitudes will be used to define the western and eastern boundaries.
The order of the longitudes is not important. The function will determine which is the minimum and maximum.
GRIB2 longitudes should be in decimal degrees with 0.0 at the prime meridian, positive values increasing eastward to 360. There are no negative GRIB2 longitudes.
The typical west longitudes that start at 0.0 at the prime meridian and decrease to -180 westward, are converted to GRIB2 longitudes by '360 - (absolute value of the west longitude)' where typical eastern longitudes are unchanged as GRIB2 longitudes.
Returns
- subset: A spatial subset of a GRIB2 message.
1840 def validate(self): 1841 """ 1842 Validate a complete GRIB2 message. 1843 1844 The g2c library does its own internal validation when g2_gribend() is called, but 1845 we will check in grib2io also. The validation checks if the first 4 bytes in 1846 self._msg is 'GRIB' and '7777' as the last 4 bytes and that the message length in 1847 section 0 equals the length of the packed message. 1848 1849 Returns 1850 ------- 1851 `True` if the packed GRIB2 message is complete and well-formed, `False` otherwise. 1852 """ 1853 valid = False 1854 if hasattr(self, "_msg"): 1855 if self._msg[0:4] + self._msg[-4:] == b"GRIB7777": 1856 if self.section0[-1] == len(self._msg): 1857 valid = True 1858 return valid
Validate a complete GRIB2 message.
The g2c library does its own internal validation when g2_gribend() is called, but we will check in grib2io also. The validation checks if the first 4 bytes in self._msg is 'GRIB' and '7777' as the last 4 bytes and that the message length in section 0 equals the length of the packed message.
Returns
Trueif the packed GRIB2 message is complete and well-formed,Falseotherwise.
2375@dataclass 2376class Grib2GridDef: 2377 """ 2378 Class for Grid Definition Template Number and Template as attributes. 2379 2380 This allows for cleaner looking code when passing these metadata around. 2381 For example, the `grib2io._Grib2Message.interpolate` method and 2382 `grib2io.interpolate` function accepts these objects. 2383 """ 2384 2385 gdtn: int 2386 gdt: NDArray 2387 2388 @classmethod 2389 def from_section3(cls, section3): 2390 return cls(section3[4], section3[5:]) 2391 2392 @property 2393 def nx(self): 2394 """Number of grid points in x-direction.""" 2395 return int(self.gdt[7]) 2396 2397 @property 2398 def ny(self): 2399 """Number of grid points in y-direction.""" 2400 return int(self.gdt[8]) 2401 2402 @property 2403 def npoints(self): 2404 """Total number of grid points.""" 2405 return int(self.gdt[7] * self.gdt[8]) 2406 2407 @property 2408 def shape(self): 2409 """Shape of the grid.""" 2410 return (int(self.ny), int(self.nx)) 2411 2412 def to_section3(self): 2413 """Return a full GRIB2 section3 array.""" 2414 return np.array([0, self.npoints, 0, 0, self.gdtn] + list(self.gdt)).astype(np.int64)
Class for Grid Definition Template Number and Template as attributes.
This allows for cleaner looking code when passing these metadata around.
For example, the grib2io._Grib2Message.interpolate method and
grib2io.interpolate function accepts these objects.
2392 @property 2393 def nx(self): 2394 """Number of grid points in x-direction.""" 2395 return int(self.gdt[7])
Number of grid points in x-direction.
2397 @property 2398 def ny(self): 2399 """Number of grid points in y-direction.""" 2400 return int(self.gdt[8])
Number of grid points in y-direction.
2402 @property 2403 def npoints(self): 2404 """Total number of grid points.""" 2405 return int(self.gdt[7] * self.gdt[8])
Total number of grid points.
652def msgs_from_index(index: dict, filehandle=None): 653 """ 654 Construct a list of Grib2Message objects from an index dictionary. 655 656 This function reconstructs a sequence of `Grib2Message` instances using 657 metadata sections stored in an index dictionary. If an open file handle is 658 provided, each message is linked to its on-disk binary data through a 659 `Grib2MessageOnDiskArray`, allowing deferred reading of the actual data 660 values from the GRIB2 file. 661 662 Parameters 663 ---------- 664 index : dict 665 Dictionary containing parsed GRIB2 index information, including 666 section data arrays such as ``section0`` through ``section5``, 667 ``sectionOffset``, ``offset``, and ``bmapflag``. 668 filehandle : file-like object, optional 669 An open binary file handle to the GRIB2 file corresponding to the index. 670 If provided, the returned messages can access on-disk data arrays via 671 memory offsets. If not provided, only metadata will be available. 672 673 Returns 674 ------- 675 list of Grib2Message 676 List of reconstructed `Grib2Message` objects built from the provided 677 index. Each message contains metadata, and if `filehandle` is given, 678 also references to on-disk data through a `Grib2MessageOnDiskArray`. 679 680 Notes 681 ----- 682 - Each message is constructed by zipping the corresponding section entries 683 (sections 0–5 and bitmap flags). 684 - When a file handle is supplied, each message’s `_ondiskarray` attribute is 685 initialized to allow direct access to GRIB2 data values without loading 686 them fully into memory. 687 - The `_msgnum` attribute of each message is assigned sequentially to 688 preserve message order. 689 """ 690 n = len(index["section4"]) 691 692 def _expand(lst): 693 if len(lst) < n: 694 return [lst[0].copy() for _ in range(n)] 695 return lst 696 697 zipped = zip( 698 _expand(index["section0"]), 699 _expand(index["section1"]), 700 index["section2"], 701 _expand(index["section3"]), 702 index["section4"], 703 index["section5"], 704 index["bmapflag"], 705 ) 706 msgs = [Grib2Message(*sections) for sections in zipped] 707 708 if filehandle is not None: 709 for n, (msg, offset, secpos) in enumerate(zip(msgs, index["offset"], index["sectionOffset"])): 710 msg._ondiskarray = Grib2MessageOnDiskArray( 711 shape=(msg.ny, msg.nx), 712 ndim=2, 713 dtype=TYPE_OF_VALUES_DTYPE[msg.typeOfValues], 714 filehandle=filehandle, 715 # A weak reference: the message holds this array, so a strong one would make a reference cycle, and 716 # the message with its decoded data would outlive every user reference until a garbage collection. 717 msg=weakref.proxy(msg), 718 offset=offset, 719 bitmap_offset=secpos[6], 720 data_offset=secpos[7], 721 ) 722 msg._msgnum = n 723 return msgs
Construct a list of Grib2Message objects from an index dictionary.
This function reconstructs a sequence of Grib2Message instances using
metadata sections stored in an index dictionary. If an open file handle is
provided, each message is linked to its on-disk binary data through a
Grib2MessageOnDiskArray, allowing deferred reading of the actual data
values from the GRIB2 file.
Parameters
- index (dict):
Dictionary containing parsed GRIB2 index information, including
section data arrays such as
section0throughsection5,sectionOffset,offset, andbmapflag. - filehandle (file-like object, optional): An open binary file handle to the GRIB2 file corresponding to the index. If provided, the returned messages can access on-disk data arrays via memory offsets. If not provided, only metadata will be available.
Returns
- list of Grib2Message: List of reconstructed
Grib2Messageobjects built from the provided index. Each message contains metadata, and iffilehandleis given, also references to on-disk data through aGrib2MessageOnDiskArray.
Notes
- Each message is constructed by zipping the corresponding section entries (sections 0–5 and bitmap flags).
- When a file handle is supplied, each message’s
_ondiskarrayattribute is initialized to allow direct access to GRIB2 data values without loading them fully into memory. - The
_msgnumattribute of each message is assigned sequentially to preserve message order.