Source code for arlmet.record

"""
The records of an ARL meteorology file.

:class:`DataRecord` is one packed 2-D field. :class:`Header` is the 50-byte
header at the front of every record (time, level, variable, packing
constants), and :class:`IndexRecord` the record that opens each time step
(grid, vertical axis, the variables on each level, as :class:`LvlInfo` and
:class:`VarInfo`). Most code reads them through :class:`arlmet.File`.
"""

from __future__ import annotations

import io
from typing import TYPE_CHECKING, Any, Literal

import numpy as np
import numpy.typing as npt
import pandas as pd
from typing_extensions import override

from arlmet._exceptions import ARLFormatError
from arlmet._grid import Grid, GridWindow, _split_at_seam
from arlmet._header import Header, record_length_from_grid, split_grid_component
from arlmet._indexrecord import IndexRecord, LvlInfo, VarInfo
from arlmet._pack import pack_core as _pack_core
from arlmet.packing import calculate_checksum, unpack
from arlmet.vertical import VerticalAxis

if TYPE_CHECKING:
    import xarray as xr

    from arlmet._recordset import RecordSet

__all__ = ["DataRecord", "Header", "IndexRecord", "LvlInfo", "VarInfo"]

# HYSPLIT's reader (metinp.f) adds each DIF record into a field it picks by the
# DIF's name. Above the surface, DIFW goes into the vertical velocity (filled by
# WWND or DZDT) and DIFT into the TKE (TKEN or TKEU); any other name is skipped.
# At the surface it matches the first three letters only, so every DIF* name goes
# into the precipitation (TPP* or PRT*). The field holds the last of its records
# read on the level, so a DIF corrects the nearest such record before it.
_UPPER_DIF_PARENTS = {"DIFW": ("WWND", "DZDT"), "DIFT": ("TKEN", "TKEU")}
_SURFACE_DIF_PARENTS = ("TPP", "PRT")

#: The name in a record header that marks the record missing, whatever its
#: index record lists (old converters wrote it for fields they never filled).
_MISSING_NAME = "NULL"


def _is_missing(header: Header) -> bool:
    """
    Return True when *header* marks its record as missing data.

    HYSPLIT's reader (``metinp.f``) skips a record whose forecast hour is
    negative or whose name is ``NULL``; its writer starts every record of a
    time step so (``pakini.f``: forecast hour -1) before a converter fills it.
    """
    return header.forecast < 0 or header.variable == _MISSING_NAME


def _checked_header(record: DataRecord, raw: bytes) -> Header:
    """
    Parse the header at the start of *raw* and check it is *record*'s.

    A header named ``NULL`` passes whatever variable the index lists: it marks
    the record missing (:func:`_is_missing`).
    """
    header = Header.from_bytes(raw[: Header.N_BYTES])
    if (
        header.variable not in (record.variable, _MISSING_NAME)
        or header.level != record.level
    ):
        raise ARLFormatError(
            f"DataRecord header mismatch at position {record.position}: "
            f"expected variable '{record.variable}' level {record.level}, "
            f"got variable '{header.variable}' level '{header.level}'"
        )
    return header


def _missing_payload(n_bytes: int) -> npt.NDArray[np.uint8]:
    """Return the packed bytes ``pakini.f`` writes for a missing record: spaces, a CR last."""
    payload = np.full(n_bytes, ord(" "), dtype=np.uint8)
    payload[-1] = 13
    return payload


def _corrects(dif: str, parent: str, level: int) -> bool:
    """Return True when a ``dif`` record at ``level`` corrects a ``parent`` record."""
    if level == 0:
        return parent[:3] in _SURFACE_DIF_PARENTS
    return parent in _UPPER_DIF_PARENTS.get(dif, ())


def _dif_parents(dif: str, level: int) -> str:
    """Name the records a ``dif`` record at ``level`` corrects, for a message."""
    if level == 0:
        return "TPP* or PRT* (at the surface, any DIF* name)"
    parents = _UPPER_DIF_PARENTS.get(dif)
    if parents is None:
        return "no record (above the surface only DIFW and DIFT correct one)"
    return " or ".join(parents)


def _check_dif_parent(dif: str, parent: str, level: int) -> None:
    """Raise ValueError unless a ``dif`` record at ``level`` corrects ``parent``."""
    if not dif.startswith("DIF"):
        raise ValueError(f"Difference record names must start with 'DIF', got '{dif}'.")
    if not _corrects(dif, parent, level):
        raise ValueError(
            f"A {dif} record at level {level} corrects {_dif_parents(dif, level)}, "
            f"not {parent}: a DIF record is paired with its parent by HYSPLIT's "
            "name table."
        )


def _check_variable_name(variable: str) -> None:
    """Raise ValueError unless *variable* is exactly four characters, as ARL stores it."""
    if len(variable) != 4:
        raise ValueError(
            f"Variable names must be exactly 4 characters, got '{variable}': "
            "a shorter name would be padded in the file and not match when read back."
        )


def _fill_masked(value: Any) -> Any:
    """
    Return a masked array with its masked cells as NaN; anything else unchanged.

    ``np.asarray`` drops a mask and keeps the values under it (netCDF readers
    leave a fill value such as 1e20 there), and one such value ruins a packed
    field. A masked cell is a missing one, which the writers already handle as NaN.
    """
    if np.ma.isMaskedArray(value):
        floats = value.astype(np.result_type(value.dtype, np.float32))
        return np.ma.filled(floats, np.nan)
    return value


def _check_field_shape(
    value: Any, grid: Grid, variable: str, level: int
) -> npt.NDArray[Any]:
    """Return *value* as an array, or raise if it is not the grid's ``(ny, nx)``."""
    array = np.asarray(_fill_masked(value))
    shape = (grid.ny, grid.nx)
    if array.shape != shape:
        raise ValueError(
            f"Data for {variable} at level {level} has shape {array.shape}, "
            f"but the grid is {shape} (ny, nx)."
        )
    return array


def _require_mode(obj: Any, *allowed_modes: str) -> None:
    """Raise UnsupportedOperation when *obj.mode* is not in *allowed_modes*."""
    if not hasattr(obj, "mode") or obj.mode not in allowed_modes:
        raise io.UnsupportedOperation(
            f"Operation only available in mode(s) {allowed_modes}, "
            f"not '{getattr(obj, 'mode', 'unknown')}'."
        )


[docs] class DataRecord: """ One ARL data record representing a single 2D variable slice. Parameters ---------- recordset : RecordSet Parent record set for the record. position : int Byte offset of the record on disk, or ``-1`` for a writable in-memory record. level : int ARL vertical level index. variable : str Four-character ARL variable name. forecast : int, optional Forecast hour required when constructing a writable record. checksum : int, optional Stored ARL checksum from the index record. reserved : str, optional Reserved one-character metadata from the index record. Attributes ---------- ndim : int NumPy-style dimensionality, always ``2``. recordset : RecordSet Parent record set. position : int Byte position of the record in the file. level : int ARL level index. variable : str Variable name for the record. shape : tuple[int, int] Grid shape as ``(ny, nx)``. data : array-like Cached unpacked data, loaded lazily on first access. Methods ------- read(window=None) Unpack the record from disk, optionally for a subset window. verify_checksum() Validate the packed bytes against the stored checksum. """ ndim: int = 2 def __init__( self, recordset: RecordSet, position: int, level: int, variable: str, forecast: int | None = None, checksum: int | None = None, reserved: str | None = None, ): """ Initialize the array representation. """ self.recordset = recordset self.position = position self.level = level self.variable = variable # Cached attributes self._header: Header | dict[str, Any] | None = None # Record header self._bytes: bytes | None = None # The packed record bytes self._packed: npt.NDArray[np.uint8] | None = None # Packed payload self._unpacked: npt.NDArray[Any] | None = None # The unpacked data self._diffs: list[DataRecord] = [] # The DIF records after this one self._derive_diff_on_pack = False self._checksum = checksum # The stored checksum if applicable self._reserved = reserved # Reserved field if applicable if self.mode == "w" and forecast is None: raise ValueError( "Forecast hour must be specified when creating a new DataRecord." ) elif forecast is not None: if self.mode == "r": raise ValueError( "Forecast hour should not be specified when reading an existing DataRecord." ) else: self._header = {"forecast": forecast} def _create_diff( self, position: int, variable: str, forecast: int | None = None, checksum: int | None = None, reserved: str | None = None, ) -> DataRecord: """ Attach a DIF record after this record and any DIF records it already has. Returns ------- DataRecord The new DIF record. """ if not variable.startswith("DIF"): raise ValueError( f"Difference record names must start with 'DIF', got '{variable}'." ) if self.mode == "w" and forecast is None: if isinstance(self._header, dict): forecast = self._header.get("forecast") elif isinstance(self._header, Header): forecast = self._header.forecast diff = DataRecord( recordset=self.recordset, position=position, variable=variable, level=self.level, forecast=forecast, checksum=checksum, reserved=reserved, ) self._diffs.append(diff) return diff @property def mode(self) -> Literal["r", "w"]: """Access mode of the record, inferred from its position.""" return "w" if self.position == -1 else "r" @property def diffs(self) -> tuple[DataRecord, ...]: """ The ``DIF*`` records that correct this record, in stream order. A ``DIF*`` record holds what packing lost from its parent: the original values minus the packed ones. It is paired with its parent by HYSPLIT's name table: ``DIFW`` corrects ``WWND`` or ``DZDT``, ``DIFT`` corrects ``TKEN`` or ``TKEU``, and at the surface any ``DIF*`` corrects ``TPP*`` or ``PRT*``, in each case the nearest such record before it on its level. A record has none, one, or, rarely, several; :meth:`read` returns the record plus each of them, added in stream order, as HYSPLIT does. See Also -------- arlmet.DataRecord.read : The record's values with its DIF records added. Examples -------- >>> record = met[0][(1, "WWND")] # doctest: +SKIP >>> [dif.variable for dif in record.diffs] # doctest: +SKIP ['DIFW'] """ return tuple(self._diffs) @property def bytes(self) -> bytes: """ Get the packed bytes for this data record. """ if self._bytes is None: if self.mode == "r": self._bytes = self.recordset.file._read_at(self.position, self.n_bytes) else: # Pack data to get bytes packed = self._pack() self._bytes = b"".join((self.header.tobytes(), packed.data)) assert self._bytes is not None return self._bytes @property def n_bytes(self) -> int: """ Get the number of bytes in the packed data record (including the header). """ return record_length_from_grid(grid=self.grid) @property def header(self) -> Header: """ Header of this data record. Read from the file in read mode, and checked against the record's variable and level; built from the record's data in write mode. """ if not isinstance(self._header, Header): if self.mode == "r": self._header = _checked_header( self, self.recordset.file._read_at(self.position, Header.N_BYTES) ) else: if not isinstance(self._header, dict): raise ValueError( "Header state must be a dictionary before constructing a writable record header." ) header_state = self._header if ( not {"precision", "exponent", "initial_value"} <= header_state.keys() ): self._pack() header_state = self._header if not isinstance(header_state, dict): raise ValueError( "Writable header state must remain mutable until the header is built." ) time = self.recordset.time forecast = header_state.get("forecast") exponent = header_state.get("exponent") precision = header_state.get("precision") initial_value = header_state.get("initial_value") if forecast is None: raise ValueError( "Forecast hour must be set to construct header in write mode." ) if exponent is None or precision is None or initial_value is None: raise ValueError( "Precision, exponent, and initial value must be set to construct header in write mode." ) grid = ( split_grid_component(self.grid.nx)[0], split_grid_component(self.grid.ny)[0], ) self._header = Header( year=time.year, month=time.month, day=time.day, hour=time.hour, forecast=int(forecast), level=self.level, grid=grid, variable=self.variable, exponent=int(exponent), precision=float(precision), initial_value=float(initial_value), ) return self._header @property def source(self) -> str: """ Get the source associated with this data record. """ return self.recordset.source @property def grid(self) -> Grid: """ Get the grid associated with this data record. """ return self.recordset.grid @property def vertical_axis(self) -> VerticalAxis: """ Get the vertical axis associated with this data record. """ return self.recordset.vertical_axis @property def time(self) -> pd.Timestamp: """ Get the time associated with this data record. """ return self.recordset.time @property def forecast(self) -> int: """ Get the forecast hour for this data record. """ return self.header.forecast @property def checksum(self) -> int: """ Get the stored checksum for this data record. A stored 0 means no checksum was recorded: a computed checksum is 0 only when every packed byte is 0. NOAA's GDAS and NAM12 files store 0 for the fields taken from a 6-hour forecast. """ if self._checksum is None: if self.mode == "r": raise ValueError("No stored checksum for this data record.") else: raise ValueError( "Data must be packed before accessing checksum in write mode." ) return self._checksum
[docs] def verify_checksum(self) -> bool: """ Verify the packed payload against the checksum stored in metadata. A stored checksum of 0 means none was recorded, so there is nothing to compare and the record is not reported as a mismatch. HYSPLIT's writer sets every checksum of a time step to 0 and fills in a record's checksum only when it packs that record, and HYSPLIT does not compare checksums when it reads a file. NOAA's GDAS and NAM12 files store 0 for the precipitation and fluxes taken from a 6-hour forecast (at 00, 06, 12 and 18 UTC), and their values are good. Returns ------- bool False if the record has a stored checksum that the packed payload does not match, True otherwise. See Also -------- arlmet.DataRecord.checksum : The stored checksum. arlmet.packing.calculate_checksum : The checksum of a packed payload. """ if self.mode == "r": packed = self.recordset.file._read_at( self.position + Header.N_BYTES, self.n_bytes - Header.N_BYTES ) else: packed = self._pack().tobytes() stored = self.checksum if stored == 0: # none recorded return True return calculate_checksum(packed=packed) == stored
@property def dtype(self) -> np.dtype[Any]: """Data type of the unpacked data (float32 until the data is read).""" if self._unpacked is None: # Data not loaded yet; assume float32 return np.dtype(np.float32) return self._unpacked.dtype @property def shape(self) -> tuple[int, int]: """Return the shape of the data grid.""" grid = self.grid return (grid.ny, grid.nx) @override def __repr__(self) -> str: t = self.time.strftime("%Y-%m-%d %H:%M") return f"DataRecord({self.variable!r}, level={self.level}, time={t})" @property def data(self) -> npt.NDArray[Any]: """ Get the data for this record. The first access reads and unpacks the full grid and caches it on the record; later accesses return the cached array. Use :meth:`read` for an uncached read. Returns ------- array-like The data array for this record. """ if self._unpacked is None: if self.mode == "r": self._unpacked = self.read() else: raise ValueError("No data to read.") return self._unpacked def __array__( self, dtype: np.dtype[Any] | None = None, copy: bool | None = None ) -> npt.NDArray[Any]: array = np.asarray(self.data) if dtype and np.dtype(dtype) != array.dtype: return array.astype(dtype) if copy: return array.copy() return array def __getitem__(self, key: Any) -> npt.NDArray[Any] | np.generic: return self.data[key]
[docs] def read(self, window: GridWindow | None = None) -> npt.NDArray[np.float32]: """ Read and unpack this record from disk. Each call returns a new array and nothing is cached on the record, so reading many records does not accumulate memory. Use :attr:`data` for a cached full-grid copy. Each of the record's :attr:`diffs` is added, in stream order, as HYSPLIT does. A record flagged missing (a negative forecast hour in its header, or the name ``NULL``) reads as NaN, and a missing ``DIF*`` record adds nothing: HYSPLIT's reader skips both. :meth:`arlmet.File.check` lists such records. Parameters ---------- window : GridWindow, optional Spatial subset to unpack. When omitted, the full grid is read. A window across the seam of a lat/lon grid that spans 360 degrees (``x_stop`` past ``nx``) reads its columns in that order, wrapping from the last column to the first. Returns ------- numpy.ndarray Unpacked ``float32`` array for the full field or the requested window, NaN where the record is flagged missing. """ _require_mode(self, "r") unpacked = self._read_own(window) if unpacked is None: shape = self.shape if window is None else window.shape return np.full(shape, np.nan, dtype=np.float32) for diff in self._diffs: correction = diff._read_own(window) if correction is not None: unpacked = unpacked + correction return unpacked
def _read_own(self, window: GridWindow | None) -> npt.NDArray[np.float32] | None: """Unpack this record alone, without its DIF records; None if it is missing.""" raw = self.recordset.file._read_at(self.position, self.n_bytes) header = self._header if not isinstance(header, Header): header = _checked_header(self, raw) self._header = header if _is_missing(header): return None # A memoryview, as slicing bytes would copy the whole field. payload = memoryview(raw)[Header.N_BYTES :] parts = (None,) if window is None else _split_at_seam(window, self.grid) pieces = [ unpack( packed=payload, nx=self.grid.nx, ny=self.grid.ny, precision=header.precision, exponent=header.exponent, initial_value=header.initial_value, window=part, ) for part in parts ] return pieces[0] if len(pieces) == 1 else np.hstack(pieces)
[docs] def to_xarray(self, *, squeeze: bool = True) -> xr.DataArray: """ Convert this DataRecord to an xarray.DataArray. Parameters ---------- squeeze : bool, optional Whether to squeeze singleton dimensions. Default is True. Returns ------- xarray.DataArray An xarray view of this data record. """ import xarray as xr da = xr.DataArray( data=self.data, dims=self.grid.dims, coords=self.grid.calculate_coords(), name=self.variable, ) da = da.expand_dims(("time", "level")) da = da.assign_coords( time=[self.time], level=[float(self.vertical_axis.levels[self.level])], ) da.attrs["source"] = self.recordset.source return da.squeeze() if squeeze else da
def __setitem__(self, key: Any, value: Any) -> None: _require_mode(self, "w") if self._unpacked is None: is_full_slice = key == slice(None) if key is Ellipsis or is_full_slice: # Setting the entire array self._unpacked = _check_field_shape( value, self.grid, self.variable, self.level ) else: raise ValueError("Data must be initialized before setting slices.") self._unpacked[key] = _fill_masked(value) self._invalidate_write_cache() def _invalidate_write_cache(self) -> None: """ Clear cached packed/header state after a writable record changes. """ if self.mode != "w": return forecast = None if isinstance(self._header, dict): forecast = self._header.get("forecast") elif isinstance(self._header, Header): forecast = self._header.forecast self._header = {"forecast": forecast} self._packed = None self._bytes = None self._checksum = None for diff in self._diffs: diff._header = {"forecast": forecast} diff._packed = None diff._bytes = None diff._checksum = None def _pack(self) -> npt.NDArray[np.uint8]: """Pack cached unpacked data and update header state for writing.""" _require_mode(self, "w") if self._packed is None: if not isinstance(self._unpacked, np.ndarray): raise ValueError("Data to pack must be a numpy array.") if not isinstance(self._header, dict): raise ValueError( "Header must be a dictionary in write mode before packing." ) field = np.ascontiguousarray(self._unpacked, dtype=np.float32) try: # The C core refuses a non-finite value as it scans the field # and returns the checksum of what it packed. packed, precision, exponent, initial_value, checksum = _pack_core(field) except ValueError: # Only a field the core refused is looked at again. missing = np.isnan(field) if missing.all(): # A field of NaN is missing data, as a missing record reads. return self._pack_missing() n_missing = int(np.count_nonzero(missing)) if n_missing: raise ValueError( f"{self.variable} at level {self.level} has {n_missing} " "missing (NaN or masked) cells; an ARL field has no missing " "cells, so it must be complete or entirely missing." ) from None if not np.isfinite(field).all(): raise ValueError( f"{self.variable} at level {self.level} has infinite values " "(or values too large for float32); ARL packs finite values " "only." ) from None raise self._packed = packed self._header["precision"] = precision self._header["exponent"] = exponent self._header["initial_value"] = initial_value self._checksum = checksum if self._derive_diff_on_pack: # Each DIF is what packing left of the target after this record # and the DIF records before it, so a reader that adds them in # order (as HYSPLIT does) gets back to the target. reconstructed = self._unpack_packed() for diff in self._diffs: diff._unpacked = np.asarray( self._unpacked - reconstructed, dtype=np.float32 ) diff._invalidate_write_cache() diff._pack() reconstructed = reconstructed + diff._unpack_packed() else: for diff in self._diffs: if diff._packed is None: diff._pack() return self._packed def _pack_missing(self) -> npt.NDArray[np.uint8]: """ Pack this record, and its DIF records, as missing, as ``pakini.f`` does. Forecast hour -1, no precision, exponent or first value, spaces for the packed values, and no checksum (HYSPLIT's index gets 0 for a record it never packed). Readers then skip it, HYSPLIT's and arlmet's alike. """ packed = _missing_payload(self.grid.nx * self.grid.ny) self._packed = packed self._header = { "forecast": -1, "precision": 0.0, "exponent": 0, "initial_value": 0.0, } self._checksum = 0 for diff in self._diffs: diff._unpacked = np.full(self.shape, np.nan, dtype=np.float32) diff._pack_missing() return packed def _unpack_packed(self) -> npt.NDArray[np.float32]: """Unpack this writable record's packed payload, as a reader would.""" if self._packed is None or not isinstance(self._header, dict): raise ValueError("Record must be packed before it is unpacked.") return unpack( packed=self._packed.tobytes(), nx=self.grid.nx, ny=self.grid.ny, precision=self._header["precision"], exponent=self._header["exponent"], initial_value=self._header["initial_value"], ) def _flush(self) -> None: """ Flush the packed data to disk and release the in-memory copies. """ _require_mode(self, "w") raw = self.bytes fh = self.recordset.file.handle if self.position == -1: # New writable records are normally flushed sequentially, so append # at the current offset and avoid an extra seek. self.position = fh.tell() elif fh.tell() != self.position: fh.seek(self.position) fh.write(raw) # The record now lives on disk (mode "r"), so drop the unpacked, # packed, and byte copies. Otherwise a written File holds ~6x its # size in memory until it is garbage collected. self._unpacked = None self._packed = None self._bytes = None