Source code for seagrid.utils

"""Helpers from seagrid 2.x: date ranges, directories, netCDF checks, subsetting.

New code uses the :class:`~seagrid.sources.DataSource` members instead
(``dtm_vec``, ``datadir``, ``downloaded``, ``open_dataset(bbox=...)``).
"""

from __future__ import annotations

import logging
import os
import pathlib
import warnings
from collections.abc import Mapping
from typing import Any

import pandas as pd
import xarray as xr

from seagrid.utils.lldist import ll2dist2vec

__all__ = [
    "datadir",
    "dtm_vec",
    "has_nc_data_var",
    "is_nc_file",
    "ll2dist2vec",
    "slice_dataframe",
    "vprint",
]

log = logging.getLogger("seagrid.utils")


[docs] def dtm_vec(settings: Mapping[str, Any]) -> pd.DatetimeIndex: """Generate a pandas date range from a settings dictionary. Parameters ---------- settings : dict Dictionary containing the keys ``dtm_min``, ``dtm_max``, and ``dtm_freq`` which are forwarded to ``pandas.date_range``. Returns ------- pandas.DatetimeIndex Date range spanning from ``dtm_min`` to ``dtm_max`` at the frequency given by ``dtm_freq``. """ return pd.date_range( settings["dtm_min"], settings["dtm_max"], freq=settings["dtm_freq"] )
[docs] def datadir(settings: Mapping[str, Any]) -> str: """Create and return the data directory path from a settings dictionary. The directory (and any missing parents) is created if it does not already exist. Parameters ---------- settings : dict Dictionary containing the key ``datadir`` with the desired directory path. Returns ------- str The data directory path stored in ``settings["datadir"]``. """ pathlib.Path(settings["datadir"]).mkdir(parents=True, exist_ok=True) return str(settings["datadir"])
[docs] def is_nc_file(full_filename: str | os.PathLike[str]) -> bool: """Check if a file exists and is a valid netCDF file. Attempts to open the file with ``xarray.open_dataset``. If the file does not exist or cannot be opened, ``False`` is returned. Parameters ---------- full_filename : str Absolute or relative path to the file to check. Returns ------- bool ``True`` if the file exists and can be opened as a netCDF dataset, ``False`` otherwise. """ if not os.path.isfile(full_filename): return False try: with xr.open_dataset(full_filename): pass except (OSError, ValueError): return False return True
[docs] def has_nc_data_var(full_filename: str | os.PathLike[str], data_var: str) -> bool: """Check if a netCDF file contains a specific data variable. The file is opened with ``xarray.open_dataset`` and the presence of *data_var* is verified. Parameters ---------- full_filename : str Path to the netCDF file. data_var : str Name of the variable to look for in the dataset. Returns ------- bool ``True`` if the file exists, is a valid netCDF file, and contains *data_var*; ``False`` otherwise. """ if not os.path.exists(full_filename): return False try: with warnings.catch_warnings(): warnings.simplefilter("ignore") with xr.open_dataset(full_filename) as ds: return data_var in ds except (OSError, ValueError): return False
[docs] def vprint(text: str, verbose: bool = False) -> None: """Log *text* at INFO level, or WARNING level if *verbose*. In 2.x this printed when the ``verbose`` setting was on. Configure the ``seagrid`` logger instead. Parameters ---------- text : str The message. verbose : bool, optional Log at WARNING level so the message is shown by default. """ log.log(logging.WARNING if verbose else logging.INFO, text)
[docs] def slice_dataframe( ds: xr.Dataset, settings: Mapping[str, Any], latname: str = "lat", lonname: str = "lon", ) -> xr.Dataset: """Subset an xarray Dataset to a lat/lon bounding box from settings. Parameters ---------- ds : xarray.Dataset The dataset to subset. settings : dict Dictionary with keys ``latmin``, ``latmax``, ``lonmin``, and ``lonmax`` defining the bounding box in degrees. latname : str, optional Name of the latitude coordinate in *ds*. Default is ``"lat"``. lonname : str, optional Name of the longitude coordinate in *ds*. Default is ``"lon"``. Returns ------- xarray.Dataset The subset of *ds* whose coordinates fall within the bounding box defined by *settings*. """ la = ds.coords[latname] lc = ds.coords[lonname] return ds.loc[ { lonname: lc[(lc >= settings["lonmin"]) & (lc <= settings["lonmax"])], latname: la[(la >= settings["latmin"]) & (la <= settings["latmax"])], } ]