diff --git a/docs/user/environment/1-atm-models/forecast.rst b/docs/user/environment/1-atm-models/forecast.rst index 17c8c3619..b79a6d5b2 100644 --- a/docs/user/environment/1-atm-models/forecast.rst +++ b/docs/user/environment/1-atm-models/forecast.rst @@ -23,6 +23,31 @@ Other generic forecasts can also be imported. the same kind of pressure-level forecast as plain JSON, see :ref:`open_meteo`. +.. note:: + + Within one Python session, RocketPy keeps in memory the forecasts it + downloaded with the shortcuts on this page (``file="GFS"``, ``"NAM"`` and + so on), so that asking again for the same forecast, as when a notebook + cell is run again, takes a couple of seconds instead of a full download. + When the same model, place and launch time are asked for again, it asks + the server which model run is current and downloads the data again only + if the server published something new. Each forecast takes about 50 kB of + memory and the 100 most recent ones are kept. + + To keep forecasts between sessions, pass ``cache=True``: + + .. code-block:: python + + env.set_atmospheric_model(type="Forecast", file="GFS", cache=True) + + The forecast is then also saved on disk, in the cache folder of your + system (``~/.cache/rocketpy`` on Linux), and a later session uses it while + the server says its model run is still the latest one. If the server + cannot be reached, the saved forecast is used anyway, with a warning that + it may not be the latest. A warning tells you every time a saved forecast + is used, and forecasts saved more than 7 days ago are deleted. Without + ``cache=True`` nothing is saved on disk. + .. _global-forecast-system: diff --git a/docs/user/environment/1-atm-models/reanalysis.rst b/docs/user/environment/1-atm-models/reanalysis.rst index 3e441ea5a..2d87c198a 100644 --- a/docs/user/environment/1-atm-models/reanalysis.rst +++ b/docs/user/environment/1-atm-models/reanalysis.rst @@ -20,6 +20,16 @@ One common reanalysis dataset is the ERA5. 2021 onwards, :ref:`open_meteo` retrieves them straight from an API, with no file to download. +.. note:: + + A reanalysis can also be read from a web address (an OPeNDAP address) + instead of a local file. Pass ``cache=True`` to + :meth:`rocketpy.Environment.set_atmospheric_model` to save what RocketPy + reads on disk, in the cache folder of your system (``~/.cache/rocketpy`` on + Linux), and use it in later sessions without downloading it again. + Reanalysis data does not change, so the saved copy is always used, and a + warning says so each time. + ERA5 ---- diff --git a/docs/user/installation.rst b/docs/user/installation.rst index 7563417cb..6ad84c056 100644 --- a/docs/user/installation.rst +++ b/docs/user/installation.rst @@ -103,6 +103,7 @@ The following packages are needed in order to run RocketPy: - requests - pytz - simplekml +- platformdirs All of these packages, are automatically installed when RocketPy is installed using either ``pip`` or ``conda``. However, in case the user wants to install these packages manually, they can do so by following the instructions bellow. @@ -121,6 +122,7 @@ The packages needed can be installed via ``pip`` by running the following lines pip install requests pip install pytz pip install simplekml + pip install platformdirs Installing Required Packages Using ``conda`` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/requirements.txt b/requirements.txt index 85fbc96ea..5ffe8e8fd 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,5 +4,6 @@ matplotlib>=3.9.0 # Released May 15th 2024 netCDF4>=1.6.4 requests pytz +platformdirs # system cache folder of Environment.set_atmospheric_model(cache=True) simplekml dill diff --git a/rocketpy/environment/atmosphere_cache.py b/rocketpy/environment/atmosphere_cache.py deleted file mode 100644 index 261d2aeca..000000000 --- a/rocketpy/environment/atmosphere_cache.py +++ /dev/null @@ -1,644 +0,0 @@ -"""Disk cache for downloaded atmospheric datasets (netCDF profiles and JSON). - -Cache root defaults to ``~/.rocketpy_cache/atmosphere``. Override the root with -the ``ROCKETPY_CACHE`` environment variable (the ``atmosphere`` subfolder is -created under it), or disable caching entirely by setting it to one of ``0``, -``off``, ``false``, ``no``, ``none`` or ``disabled``. - -OPeNDAP "Best" aggregations are virtual catalogs, not downloadable files. For -Forecast/Ensemble shortcuts this module therefore stores the **location-and-time -profiles** RocketPy extracts after the first successful fetch, as a compact -``.nc`` file, together with every derived attribute ``Environment`` publishes -for that model (date range, grid bounds and the raw interpolation inputs) so a -cache hit reproduces the same object a fresh download would have produced. -Windy responses are stored as ``.json``. - -Forecasts are re-issued by their providers on a fixed cycle, so cache entries -expire after ``ROCKETPY_CACHE_TTL`` seconds (default: 6 hours, matching the GFS -cycle). Reanalysis data is immutable and never expires. Set the TTL to ``0`` to -disable expiry. -""" - -from __future__ import annotations - -import json -import os -import re -import shutil -import tempfile -import time -import warnings -from datetime import datetime -from pathlib import Path - -import netCDF4 -import numpy as np - -CACHE_ENV_VAR = "ROCKETPY_CACHE" -CACHE_TTL_ENV_VAR = "ROCKETPY_CACHE_TTL" -DEFAULT_CACHE_ROOT = Path.home() / ".rocketpy_cache" -PROFILE_FORMAT_ATTR = "rocketpy_atmosphere_profiles_v2" -JSON_FORMAT_KEY = "rocketpy_cache_format" -CREATED_AT_ATTR = "rocketpy_cache_created_at" -DEFAULT_CACHE_TTL_SECONDS = 6 * 3600 - -#: Model kinds whose data never changes once published, so they never expire. -IMMUTABLE_KINDS = frozenset({"reanalysis"}) - -_DISABLED_VALUES = frozenset({"", "0", "off", "false", "no", "none", "disabled"}) -_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S" - -#: Raised by ``netCDF4.Dataset`` when a file cannot be opened at all: a damaged, -#: empty or truncated file gives ``OSError``, a missing one ``FileNotFoundError`` -#: and an unwritable location ``PermissionError`` (both ``OSError`` subclasses). -#: ``RuntimeError`` is listed because netCDF4 surfaces some HDF5-level failures -#: that way, and the installed version is not pinned. -CACHE_OPEN_ERRORS = (OSError, RuntimeError) - -#: Everything the above can raise, plus what reading or writing the contents of -#: an otherwise-openable cache file can raise. Verified against netCDF4 1.7.4: -#: a missing variable raises ``KeyError``; a missing or non-numeric attribute -#: ``AttributeError``; a wrong-length array or an undeclared dimension -#: ``ValueError``; an invalid dtype or attribute type ``TypeError``; and -#: touching a closed dataset ``RuntimeError``. -#: -#: The list is deliberately explicit rather than a bare ``except Exception``: a -#: corrupt cache entry must degrade to a re-download, but a ``NameError`` or any -#: other genuine defect in this module has to keep propagating instead of being -#: silently reported to the user as a cache miss. -CACHE_FILE_ERRORS = CACHE_OPEN_ERRORS + ( - ValueError, - TypeError, - KeyError, - AttributeError, -) - -# Scalar metadata persisted as netCDF attributes, with the caster used on read. -_SCALAR_METADATA = ( - ("atmospheric_model_interval", float), - ("atmospheric_model_init_lat", float), - ("atmospheric_model_end_lat", float), - ("atmospheric_model_init_lon", float), - ("atmospheric_model_end_lon", float), - ("lat_index", int), - ("lon_index", int), -) -_DATE_METADATA = ("atmospheric_model_init_date", "atmospheric_model_end_date") -_PAIR_METADATA = ("lat_array", "lon_array", "time_array") -#: Raw interpolation inputs, shaped ``(raw_level, lat_pair, lon_pair)``. -_CORNER_METADATA = ("geopotentials", "wind_us", "wind_vs", "temperatures") - - -# --------------------------------------------------------------------------- -# Cache location and policy -# --------------------------------------------------------------------------- - - -def is_cache_enabled() -> bool: - """Return False when ``ROCKETPY_CACHE`` opts out of disk caching.""" - raw = os.environ.get(CACHE_ENV_VAR) - if raw is None: - return True - return raw.strip().lower() not in _DISABLED_VALUES - - -def get_cache_root() -> Path: - """Return the root cache directory (honors ``ROCKETPY_CACHE``).""" - return Path(os.environ.get(CACHE_ENV_VAR) or DEFAULT_CACHE_ROOT).expanduser() - - -def get_atmosphere_cache_dir() -> Path: - """Return the atmosphere subdirectory under the cache root.""" - return get_cache_root() / "atmosphere" - - -def get_cache_ttl() -> float: - """Return the cache lifetime in seconds (``0`` disables expiry).""" - raw = os.environ.get(CACHE_TTL_ENV_VAR) - if raw is None: - return float(DEFAULT_CACHE_TTL_SECONDS) - try: - return max(float(raw), 0.0) - except (TypeError, ValueError): - warnings.warn( - f"Invalid {CACHE_TTL_ENV_VAR}='{raw}'. " - f"Using the default of {DEFAULT_CACHE_TTL_SECONDS} seconds.", - UserWarning, - stacklevel=2, - ) - return float(DEFAULT_CACHE_TTL_SECONDS) - - -def is_entry_expired(created_at, kind) -> bool: - """Return True when a cache entry written at ``created_at`` is too old. - - Entries whose ``kind`` is in :data:`IMMUTABLE_KINDS` never expire, and a - TTL of ``0`` disables expiry for every kind. - """ - if kind in IMMUTABLE_KINDS: - return False - ttl = get_cache_ttl() - if ttl <= 0: - return False - try: - age = time.time() - float(created_at) - except (TypeError, ValueError): - return True # unreadable timestamp: treat as stale and re-fetch - return age > ttl - - -def ensure_atmosphere_cache_dir() -> Path | None: - """Create the atmosphere cache directory. - - Returns - ------- - pathlib.Path or None - The directory path, or ``None`` if caching is disabled or the - directory could not be created. - """ - if not is_cache_enabled(): - return None - cache_dir = get_atmosphere_cache_dir() - try: - cache_dir.mkdir(parents=True, exist_ok=True) - return cache_dir - except OSError as exc: - warnings.warn( - f"Could not create atmosphere cache directory '{cache_dir}': {exc}. " - "Caching disabled for this request.", - UserWarning, - stacklevel=2, - ) - return None - - -def clear_atmosphere_cache() -> bool: - """Delete every cached atmosphere file. Returns False on failure.""" - cache_dir = get_atmosphere_cache_dir() - if not cache_dir.is_dir(): - return True - try: - shutil.rmtree(cache_dir) - return True - except OSError as exc: - warnings.warn( - f"Could not clear atmosphere cache '{cache_dir}': {exc}.", - UserWarning, - stacklevel=2, - ) - return False - - -def sanitize_cache_key(key: str) -> str: - """Replace characters that are unsafe in filenames.""" - return re.sub(r"[^A-Za-z0-9_.-]", "_", key) - - -def cache_path_for(key: str, suffix: str) -> Path: - """Build a cache file path for ``key`` with the given suffix (e.g. ``.nc``).""" - if not suffix.startswith("."): - suffix = f".{suffix}" - return get_atmosphere_cache_dir() / f"{sanitize_cache_key(key)}{suffix}" - - -def build_atmosphere_cache_key( - kind: str, - source: str, - latitude: float, - longitude: float, - datetime_date, - variant: str = "", -) -> str: - """Build a stable cache key for a Forecast/Ensemble/Windy request. - - ``variant`` distinguishes requests that hit the same source and location - but decode it differently (a different variable dictionary or pressure - conversion factor), which would otherwise collide on one file. - """ - if datetime_date is None: - date_part = "nodate" - else: - date_part = datetime_date.strftime("%Y%m%d%H") - key = f"{kind}_{source}_{latitude:.4f}_{longitude:.4f}_{date_part}" - if variant: - key = f"{key}_{variant}" - return sanitize_cache_key(key) - - -def is_remote_url(path_or_url) -> bool: - """Return True if ``path_or_url`` looks like an HTTP(S)/OPeNDAP URL.""" - if not isinstance(path_or_url, str): - return False - lowered = path_or_url.lower() - return lowered.startswith(("http://", "https://", "dods://")) - - -# --------------------------------------------------------------------------- -# Raw byte / JSON helpers -# --------------------------------------------------------------------------- - - -def atomic_write_bytes(path: Path, data: bytes) -> bool: - """Write ``data`` to ``path`` atomically. Returns False on failure.""" - if ensure_atmosphere_cache_dir() is None: - return False - temp_name = None - try: - path.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile( - dir=path.parent, delete=False, suffix=".tmp" - ) as handle: - handle.write(data) - temp_name = handle.name - Path(temp_name).replace(path) - return True - except OSError as exc: - warnings.warn( - f"Failed to write atmosphere cache file '{path}': {exc}.", - UserWarning, - stacklevel=2, - ) - _discard(temp_name) - return False - - -def _discard(path) -> None: - """Best-effort removal of a leftover temporary file.""" - if path is None: - return - try: - Path(path).unlink(missing_ok=True) - except OSError: - pass - - -def load_json_cache(path: Path, kind: str = "windy") -> dict | None: - """Load a JSON cache file, or ``None`` if missing/stale/unreadable.""" - if not is_cache_enabled() or not path.is_file(): - return None - try: - with path.open("r", encoding="utf-8") as handle: - envelope = json.load(handle) - except (OSError, UnicodeDecodeError, json.JSONDecodeError) as exc: - warnings.warn( - f"Failed to read cached atmosphere JSON '{path}': {exc}. " - "Fetching fresh data.", - UserWarning, - stacklevel=2, - ) - return None - - if ( - not isinstance(envelope, dict) - or envelope.get(JSON_FORMAT_KEY) != PROFILE_FORMAT_ATTR - ): - return None - if is_entry_expired(envelope.get(CREATED_AT_ATTR), kind): - return None - payload = envelope.get("payload") - return payload if isinstance(payload, dict) else None - - -def save_json_cache(path: Path, payload: dict) -> bool: - """Serialize ``payload`` as JSON to ``path``. Returns False on failure.""" - if not is_cache_enabled(): - return False - envelope = { - JSON_FORMAT_KEY: PROFILE_FORMAT_ATTR, - CREATED_AT_ATTR: time.time(), - "payload": payload, - } - try: - data = json.dumps(envelope).encode("utf-8") - except (TypeError, ValueError) as exc: - warnings.warn( - f"Failed to serialize atmosphere JSON for cache '{path}': {exc}.", - UserWarning, - stacklevel=2, - ) - return False - return atomic_write_bytes(path, data) - - -# --------------------------------------------------------------------------- -# Model metadata persistence -# --------------------------------------------------------------------------- - - -def _write_metadata(dataset, metadata) -> None: - """Store the ``Environment`` model metadata on an open netCDF dataset.""" - metadata = metadata or {} - _write_metadata_attributes(dataset, metadata) - _write_metadata_arrays(dataset, metadata) - - -def _write_metadata_attributes(dataset, metadata) -> None: - """Store the scalar, date and coordinate-pair metadata as attributes.""" - for name, _ in _SCALAR_METADATA: - value = metadata.get(name) - if value is not None: - dataset.setncattr(name, float(value)) - - for name in _DATE_METADATA: - value = metadata.get(name) - if isinstance(value, datetime): - dataset.setncattr(name, value.strftime(_DATE_FORMAT)) - - for name in _PAIR_METADATA: - value = metadata.get(name) - if value is not None: - dataset.setncattr(name, [float(item) for item in value]) - - -def _write_metadata_arrays(dataset, metadata) -> None: - """Store the raw interpolation inputs as netCDF variables.""" - raw_levels = metadata.get("levels") - if raw_levels is None: - return - - raw_levels = np.asarray(raw_levels) - dataset.setncattr( - "levels_integer", int(np.issubdtype(raw_levels.dtype, np.integer)) - ) - dataset.createDimension("raw_level", raw_levels.size) - dataset.createDimension("lat_pair", 2) - dataset.createDimension("lon_pair", 2) - - variable = dataset.createVariable("raw_levels", "f8", ("raw_level",)) - variable[:] = np.asarray(raw_levels, dtype=float) - - raw_height = metadata.get("height") - if raw_height is not None: - variable = dataset.createVariable("raw_height", "f8", ("raw_level",)) - variable[:] = _filled(raw_height) - - for name in _CORNER_METADATA: - values = metadata.get(name) - if values is None: - continue - variable = dataset.createVariable( - name, "f8", ("raw_level", "lat_pair", "lon_pair") - ) - variable[:] = _filled(values) - - -def _read_metadata(dataset) -> dict: - """Rebuild the ``Environment`` model metadata from an open netCDF dataset.""" - metadata = {} - - for name, caster in _SCALAR_METADATA: - if hasattr(dataset, name): - metadata[name] = caster(dataset.getncattr(name)) - - for name in _DATE_METADATA: - if hasattr(dataset, name): - metadata[name] = datetime.strptime(dataset.getncattr(name), _DATE_FORMAT) - - for name in _PAIR_METADATA: - if hasattr(dataset, name): - metadata[name] = [ - float(item) for item in np.atleast_1d(dataset.getncattr(name)) - ] - - if "raw_levels" in dataset.variables: - levels = np.array(dataset.variables["raw_levels"][:], dtype=float) - if int(getattr(dataset, "levels_integer", 0)): - levels = levels.astype(np.int64) - metadata["levels"] = levels - - if "raw_height" in dataset.variables: - metadata["height"] = np.array(dataset.variables["raw_height"][:], dtype=float) - - for name in _CORNER_METADATA: - if name in dataset.variables: - metadata[name] = np.array(dataset.variables[name][:], dtype=float) - - return metadata - - -def _filled(values): - """Return a plain float array, replacing any masked entries with NaN.""" - return np.ma.filled(np.ma.asarray(values).astype(float), np.nan) - - -def _open_for_write(path: Path): - """Create a temporary netCDF file next to ``path``. Returns (dataset, temp).""" - path.parent.mkdir(parents=True, exist_ok=True) - with tempfile.NamedTemporaryFile( - dir=path.parent, delete=False, suffix=".nc.tmp" - ) as handle: - temp_path = Path(handle.name) - return netCDF4.Dataset(temp_path, mode="w", format="NETCDF4"), temp_path - - -def _set_common_attributes(dataset, kind, elevation, max_expected_height) -> None: - """Write the attributes shared by every cache file format.""" - dataset.setncattr("rocketpy_cache_format", PROFILE_FORMAT_ATTR) - dataset.setncattr("rocketpy_cache_kind", kind) - dataset.setncattr(CREATED_AT_ATTR, float(time.time())) - dataset.setncattr("elevation", float(elevation)) - dataset.setncattr("max_expected_height", float(max_expected_height)) - - -def _open_valid_cache(path: Path, expected_kind=None): - """Open a cache file, returning ``None`` if absent, foreign or expired.""" - if not is_cache_enabled() or not path.is_file(): - return None - try: - dataset = netCDF4.Dataset(path, mode="r") - except CACHE_OPEN_ERRORS as exc: - # A cache miss must never be louder than the download it replaces. - warnings.warn( - f"Failed to open atmosphere cache '{path}': {exc}. Fetching fresh data.", - UserWarning, - stacklevel=2, - ) - return None - - fmt = getattr(dataset, "rocketpy_cache_format", None) - kind = getattr(dataset, "rocketpy_cache_kind", None) - if fmt != PROFILE_FORMAT_ATTR or ( - expected_kind is not None and kind != expected_kind - ): - dataset.close() - return None - if is_entry_expired(getattr(dataset, CREATED_AT_ATTR, None), kind): - dataset.close() - return None - return dataset - - -# --------------------------------------------------------------------------- -# Forecast / Reanalysis profiles -# --------------------------------------------------------------------------- - - -def write_profile_netcdf( - path: Path, - *, - height, - pressure, - temperature, - wind_u, - wind_v, - elevation: float, - max_expected_height: float, - kind: str = "forecast", - metadata=None, -) -> bool: - """Write extracted atmospheric profiles to a compact local netCDF file.""" - if ensure_atmosphere_cache_dir() is None: - return False - - columns = ( - ("height", height, "m"), - ("pressure", pressure, "Pa"), - ("temperature", temperature, "K"), - ("wind_u", wind_u, "m s-1"), - ("wind_v", wind_v, "m s-1"), - ) - temp_path = None - try: - dataset, temp_path = _open_for_write(path) - try: - _set_common_attributes(dataset, kind, elevation, max_expected_height) - dataset.createDimension("level", np.asarray(height, dtype=float).size) - for name, values, units in columns: - variable = dataset.createVariable(name, "f8", ("level",)) - variable.units = units - variable[:] = np.asarray(values, dtype=float) - _write_metadata(dataset, metadata) - finally: - dataset.close() - temp_path.replace(path) - return True - except CACHE_FILE_ERRORS as exc: - warnings.warn( - f"Failed to write atmosphere profile cache '{path}': {exc}.", - UserWarning, - stacklevel=2, - ) - _discard(temp_path) - return False - - -def read_profile_netcdf(path: Path) -> dict | None: - """Read a profile netCDF written by :func:`write_profile_netcdf`.""" - dataset = _open_valid_cache(path) - if dataset is None: - return None - try: - profiles = { - "kind": getattr(dataset, "rocketpy_cache_kind", "forecast"), - "elevation": float(dataset.getncattr("elevation")), - "max_expected_height": float(dataset.getncattr("max_expected_height")), - } - for name in ("height", "pressure", "temperature", "wind_u", "wind_v"): - profiles[name] = np.array(dataset.variables[name][:], dtype=float) - profiles["metadata"] = _read_metadata(dataset) - return profiles - except CACHE_FILE_ERRORS as exc: - warnings.warn( - f"Failed to read atmosphere profile cache '{path}': {exc}. " - "Fetching fresh data.", - UserWarning, - stacklevel=2, - ) - return None - finally: - dataset.close() - - -# --------------------------------------------------------------------------- -# Ensemble profiles -# --------------------------------------------------------------------------- - - -def write_ensemble_profile_netcdf( - path: Path, - *, - levels, - height_ensemble, - temperature_ensemble, - wind_u_ensemble, - wind_v_ensemble, - elevation: float, - max_expected_height: float, - metadata=None, -) -> bool: - """Write ensemble member profiles to a compact local netCDF file.""" - if ensure_atmosphere_cache_dir() is None: - return False - - height_ensemble = np.asarray(height_ensemble, dtype=float) - if height_ensemble.ndim != 2: - return False - num_members, num_levels = height_ensemble.shape - columns = ( - ("height", height_ensemble, "m"), - ("temperature", temperature_ensemble, "K"), - ("wind_u", wind_u_ensemble, "m s-1"), - ("wind_v", wind_v_ensemble, "m s-1"), - ) - - temp_path = None - try: - dataset, temp_path = _open_for_write(path) - try: - _set_common_attributes(dataset, "ensemble", elevation, max_expected_height) - dataset.createDimension("member", num_members) - dataset.createDimension("level", num_levels) - - level_var = dataset.createVariable("level", "f8", ("level",)) - level_var.units = "Pa" - level_var[:] = np.asarray(levels, dtype=float) - - for name, values, units in columns: - variable = dataset.createVariable(name, "f8", ("member", "level")) - variable.units = units - variable[:] = np.asarray(values, dtype=float) - _write_metadata(dataset, metadata) - finally: - dataset.close() - temp_path.replace(path) - return True - except CACHE_FILE_ERRORS as exc: - warnings.warn( - f"Failed to write ensemble atmosphere cache '{path}': {exc}.", - UserWarning, - stacklevel=2, - ) - _discard(temp_path) - return False - - -def read_ensemble_profile_netcdf(path: Path) -> dict | None: - """Read an ensemble profile netCDF written by :func:`write_ensemble_profile_netcdf`.""" - dataset = _open_valid_cache(path, expected_kind="ensemble") - if dataset is None: - return None - try: - profiles = { - "elevation": float(dataset.getncattr("elevation")), - "max_expected_height": float(dataset.getncattr("max_expected_height")), - "levels": np.array(dataset.variables["level"][:], dtype=float), - } - for key, name in ( - ("height_ensemble", "height"), - ("temperature_ensemble", "temperature"), - ("wind_u_ensemble", "wind_u"), - ("wind_v_ensemble", "wind_v"), - ): - profiles[key] = np.array(dataset.variables[name][:], dtype=float) - profiles["metadata"] = _read_metadata(dataset) - return profiles - except CACHE_FILE_ERRORS as exc: - warnings.warn( - f"Failed to read ensemble atmosphere cache '{path}': {exc}. " - "Fetching fresh data.", - UserWarning, - stacklevel=2, - ) - return None - finally: - dataset.close() diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index 8ac6f4033..abdfd4b3a 100644 --- a/rocketpy/environment/environment.py +++ b/rocketpy/environment/environment.py @@ -1,6 +1,5 @@ # pylint: disable=too-many-public-methods, too-many-instance-attributes, too-many-lines import bisect -import hashlib import json import logging import os @@ -8,24 +7,13 @@ import warnings from collections.abc import Mapping from collections import namedtuple +from copy import deepcopy from datetime import datetime import netCDF4 import numpy as np import pytz -from rocketpy.environment.atmosphere_cache import ( - build_atmosphere_cache_key, - cache_path_for, - is_cache_enabled, - is_remote_url, - load_json_cache, - read_ensemble_profile_netcdf, - read_profile_netcdf, - save_json_cache, - write_ensemble_profile_netcdf, - write_profile_netcdf, -) from rocketpy.environment.fetchers import ( fetch_aigfs_file_return_dataset, fetch_atmospheric_data_from_meteomatics, @@ -45,6 +33,7 @@ OPEN_METEO_PRESSURE_LEVELS, ) from rocketpy.environment.tools import ( + atmosphere_cache_path, calculate_wind_heading, calculate_wind_speed, convert_wind_heading_to_direction, @@ -58,9 +47,12 @@ get_final_date_from_time_array, get_initial_date_from_time_array, get_interval_date_from_time_array, + get_model_run, get_pressure_levels_from_file, + load_atmosphere, mask_and_clean_dataset, pressure_unit_to_factor, + save_atmosphere, ) from rocketpy.environment.weather_model_mapping import WeatherModelMapping from rocketpy.mathutils.function import NUMERICAL_TYPES, Function, funcify_method @@ -73,6 +65,51 @@ logger = logging.getLogger(__name__) +# Forecasts downloaded in this Python session, kept in memory. Each +# request (model, place, launch time and so on) maps to the model run that +# supplied the launch time and to what processing it set on the Environment. +_FORECASTS_IN_MEMORY = {} +# One forecast takes about 50 kB. Past this number the oldest one is dropped. +_MAX_FORECASTS_IN_MEMORY = 100 +# What process_forecast_reanalysis always sets on the Environment. Kept apart: +# the elevation, set only when the model has a surface height, and +# wind_heading and wind_direction, which are built from their unwrapped +# versions listed here. +_FORECAST_ATTRIBUTES = ( + "pressure", + "barometric_height", + "temperature", + "wind_velocity_x", + "wind_velocity_y", + "wind_speed", + "wind_heading_unwrapped", + "wind_direction_unwrapped", + "_max_expected_height", + "atmospheric_model_init_date", + "atmospheric_model_end_date", + "atmospheric_model_interval", + "atmospheric_model_init_lat", + "atmospheric_model_end_lat", + "atmospheric_model_init_lon", + "atmospheric_model_end_lon", + "lat_array", + "lon_array", + "lat_index", + "lon_index", + "geopotentials", + "wind_us", + "wind_vs", + "levels", + "temperatures", + "time_array", + "height", +) + + +def _is_web_address(file): + """Whether ``file`` is the web address of a dataset, not a local file.""" + return isinstance(file, str) and file.lower().startswith(("http://", "https://")) + class Environment: """Keeps all environment information stored, such as wind and temperature @@ -577,11 +614,7 @@ def __set_wind_angle_function(self, source, attribute, output): interpolation="linear", ) setattr(self, f"{attribute}_unwrapped", unwrapped) - source = Function( - lambda h: unwrapped(h) % 360, - inputs="Height Above Sea Level (m)", - outputs=output, - ) + source = self.__wrapped_wind_angle(unwrapped) else: source = Function( source, @@ -591,6 +624,16 @@ def __set_wind_angle_function(self, source, attribute, output): ) setattr(self, attribute, source) + @staticmethod + def __wrapped_wind_angle(unwrapped): + """Wind angle from 0 to 360 degrees as a Function of height, read from + the Function that holds the same angle unwrapped.""" + return Function( + lambda h: unwrapped(h) % 360, + inputs="Height Above Sea Level (m)", + outputs=unwrapped.get_outputs()[0], + ) + def __set_wind_direction_function(self, source): self.__set_wind_angle_function( source, "wind_direction", "Wind Direction (Deg True)" @@ -714,6 +757,161 @@ def __resolve_dictionary_for_dataset(self, dictionary, dataset): return dictionary + def __process_or_reuse_forecast( + self, file, fetch_function, dictionary, conversion_factor, cache + ): + """Download and process the forecast of one of the latest-forecast + shortcuts, or reuse one already obtained for the same request from the + same model run: kept in memory by an earlier Environment of this Python + session or, when ``cache`` is True, saved on disk. + + The server is asked which model run supplies the launch time and which + times the forecast covers. The data is downloaded and processed again + whenever that differs from what was kept, or cannot be identified. A + forecast saved on disk is also used, with a warning, when the server + cannot be reached. + + Parameters + ---------- + file : str + Name of the shortcut, such as ``"GFS"``. + fetch_function : callable + Function that opens the dataset of the shortcut on the server. + dictionary : dict + Names of the variables in the dataset. + conversion_factor : float + Factor that converts the pressure levels of the dataset to Pa. + cache : bool + Whether forecasts are read from and saved on disk. + """ + request = self.__atmosphere_request( + "forecast", file, dictionary, conversion_factor + ) + path = atmosphere_cache_path("forecast", request) if cache else None + saved = load_atmosphere(path) if cache else None + try: + # A saved forecast can stand in for the server, so one attempt is + # made instead of retrying for minutes + dataset = ( + fetch_function() if saved is None else fetch_function(max_attempts=1) + ) + except RuntimeError: + if saved is None: + raise + self.__apply_forecast_results( + saved["results"], + f"The {file} forecast server could not be reached. Using the " + "forecast saved on disk from the model run of " + f"{saved['model_run'][1]}, which may not be the latest one.", + ) + return + + model_run = get_model_run(dataset, dictionary.get("time"), self.datetime_date) + if model_run is None: + self.process_forecast_reanalysis( + dataset, dictionary, conversion_factor=conversion_factor + ) + return + kept = _FORECASTS_IN_MEMORY.get(request) + if kept is not None and kept[0] == model_run: + dataset.close() + self.__apply_forecast_results(deepcopy(kept[1])) + return + if saved is not None and tuple(saved["model_run"]) == model_run: + dataset.close() + self.__keep_forecast_in_memory(request, model_run, saved["results"]) + self.__apply_forecast_results( + saved["results"], + f"Using the {file} forecast saved on disk, from the model run of " + f"{model_run[1]}, which is still the latest one.", + ) + return + + results = self.__process_and_collect(dataset, dictionary, conversion_factor) + self.__keep_forecast_in_memory(request, model_run, results) + if cache: + save_atmosphere(path, {"model_run": model_run, "results": results}) + + def __process_or_reuse_reanalysis(self, file, dictionary, conversion_factor): + """Download and process a reanalysis given by a web address, or use the + one saved on disk for the same request. Its data never changes, so a + saved reanalysis is always used. + + Parameters + ---------- + file : str + Web address of the reanalysis dataset. + dictionary : dict + Names of the variables in the dataset. + conversion_factor : float + Factor that converts the pressure levels of the dataset to Pa. + """ + request = self.__atmosphere_request( + "reanalysis", file, dictionary, conversion_factor + ) + path = atmosphere_cache_path("reanalysis", request) + saved = load_atmosphere(path) + if saved is not None: + self.__apply_forecast_results( + saved["results"], + "Using the reanalysis saved on disk instead of downloading it " + f"again from '{file}'.", + ) + return + results = self.__process_and_collect(file, dictionary, conversion_factor) + save_atmosphere(path, {"model_run": None, "results": results}) + + def __atmosphere_request(self, kind, file, dictionary, conversion_factor): + """What identifies a download: the model, how it is read, and the + launch site and time.""" + return ( + kind, + file, + self.latitude, + self.longitude, + self.datetime_date, + conversion_factor, + tuple(sorted(dictionary.items(), key=str)), + ) + + def __process_and_collect(self, dataset, dictionary, conversion_factor): + """Process a forecast or reanalysis dataset and return what the + processing set on this Environment.""" + # The processing sets the elevation only when the model has a surface + # height, and never reads it. A placeholder tells which case this is. + elevation = self.elevation + self.elevation = placeholder = object() + try: + self.process_forecast_reanalysis( + dataset, dictionary, conversion_factor=conversion_factor + ) + finally: + sets_elevation = self.elevation is not placeholder + if not sets_elevation: + self.elevation = elevation + results = {name: getattr(self, name) for name in _FORECAST_ATTRIBUTES} + if sets_elevation: + results["elevation"] = self.elevation + return results + + def __apply_forecast_results(self, results, warning=None): + """Set on this Environment what an earlier processing set, giving + ``warning`` first if there is one.""" + if warning is not None: + warnings.warn(warning) + self.__dict__.update(results) + # Built here, so they read the values this Environment now owns + self.wind_heading = self.__wrapped_wind_angle(self.wind_heading_unwrapped) + self.wind_direction = self.__wrapped_wind_angle(self.wind_direction_unwrapped) + + @staticmethod + def __keep_forecast_in_memory(request, model_run, results): + """Keep a copy of a forecast for the rest of the Python session.""" + _FORECASTS_IN_MEMORY.pop(request, None) + _FORECASTS_IN_MEMORY[request] = (model_run, deepcopy(results)) + while len(_FORECASTS_IN_MEMORY) > _MAX_FORECASTS_IN_MEMORY: + del _FORECASTS_IN_MEMORY[next(iter(_FORECASTS_IN_MEMORY))] + def __validate_dictionary(self, file, dictionary): # removed CMC until it is fixed. available_models = [ @@ -1247,7 +1445,7 @@ def set_atmospheric_model( # pylint: disable=too-many-statements pressure_conversion_factor=None, username=None, password=None, - no_cache=False, + cache=False, ): """Define the atmospheric model for this Environment. @@ -1368,11 +1566,19 @@ def set_atmospheric_model( # pylint: disable=too-many-statements Meteomatics account password. Only used when ``type`` is ``"meteomatics"``. If None (the default), the value is read from the ``METEOMATICS_PASSWORD`` environment variable. - no_cache : bool, optional - If True, bypass the on-disk atmosphere cache and force a fresh - download for remote Forecast/Ensemble/Windy sources. Cached files - live under ``~/.rocketpy_cache/atmosphere`` (or ``ROCKETPY_CACHE``). - Default is False. + cache : bool, optional + If True, save the downloaded data on disk, in the cache folder of + the system (``~/.cache/rocketpy`` on Linux), and use it again in + later Python sessions instead of downloading it again. Only used + for the latest forecast shortcuts (``type="Forecast"`` with + ``file="GFS"``, ``"NAM"``, ``"RAP"``, ``"HRRR"`` or ``"AIGFS"``) and + for a reanalysis given by a web address. A saved forecast is used + only while the server says its model run is still the latest one, + or, with a warning, when the server cannot be reached. A saved + reanalysis is always used, since its data never changes. A + warning tells every time saved data is used. Forecasts saved more + than 7 days ago are deleted. Default is False, which saves nothing + on disk. Returns ------- @@ -1421,8 +1627,7 @@ def set_atmospheric_model( # pylint: disable=too-many-statements self.process_custom_atmosphere(pressure, temperature, wind_u, wind_v) case "windy": self.process_windy_atmosphere( - **({} if file is None else {"model": file}), - no_cache=no_cache, + **({} if file is None else {"model": file}) ) case "open_meteo": self.process_open_meteo_atmosphere( @@ -1490,14 +1695,23 @@ def set_atmospheric_model( # pylint: disable=too-many-statements except KeyError: fetch_function = None - self.__load_or_fetch_atmospheric_model( - atm_type=type, - file=file, - dictionary=dictionary, - conversion_factor=conversion_factor, - fetch_function=fetch_function, - no_cache=no_cache, - ) + if fetch_function is not None and type == "forecast": + self.__process_or_reuse_forecast( + file, fetch_function, dictionary, conversion_factor, cache + ) + elif cache and type == "reanalysis" and _is_web_address(file): + self.__process_or_reuse_reanalysis( + file, dictionary, conversion_factor + ) + else: + # Fetches the dataset using OpenDAP protocol or uses the + # file path + dataset = fetch_function() if fetch_function is not None else file + if type in ["forecast", "reanalysis"]: + process = self.process_forecast_reanalysis + else: + process = self.process_ensemble + process(dataset, dictionary, conversion_factor=conversion_factor) ground_pressure = self.pressure(self.elevation) if not 30000 <= ground_pressure <= 120_000: @@ -1535,253 +1749,6 @@ def set_atmospheric_model( # pylint: disable=too-many-statements self.atmospheric_model_file = file self.atmospheric_model_dict = dictionary - def __atmosphere_cache_path_for_request( - self, atm_type, file, fetch_function, dictionary, conversion_factor - ): - """Return a cache path for remote Forecast/Ensemble sources, else None.""" - if not is_cache_enabled(): - return None - - if fetch_function is not None and isinstance(file, str): - source_label = file - elif is_remote_url(file): - source_label = ( - "url_" - + hashlib.md5(file.encode("utf-8"), usedforsecurity=False).hexdigest()[ - :12 - ] - ) - else: - return None - - # The same source decoded with a different variable dictionary or - # pressure unit yields different profiles, so it needs its own entry. - variant = hashlib.md5( - repr((sorted(dictionary.items()), conversion_factor)).encode("utf-8"), - usedforsecurity=False, - ).hexdigest()[:8] - - return cache_path_for( - build_atmosphere_cache_key( - atm_type, - source_label, - self.latitude, - self.longitude, - self.datetime_date, - variant=variant, - ), - ".nc", - ) - - def __load_or_fetch_atmospheric_model( - self, - *, - atm_type, - file, - dictionary, - conversion_factor, - fetch_function, - no_cache, - ): - """Apply a cached model when available, otherwise fetch and cache it.""" - cache_path = self.__atmosphere_cache_path_for_request( - atm_type, file, fetch_function, dictionary, conversion_factor - ) - is_ensemble = atm_type == "ensemble" - - if cache_path is not None and not no_cache: - apply_cached = ( - self.__apply_cached_ensemble_profiles - if is_ensemble - else self.__apply_cached_forecast_profiles - ) - if apply_cached(cache_path): - return - - # Fetches the dataset using OpenDAP protocol or uses the file path - dataset = fetch_function() if fetch_function is not None else file - if is_ensemble: - self.process_ensemble( - dataset, dictionary, conversion_factor=conversion_factor - ) - else: - self.process_forecast_reanalysis( - dataset, dictionary, conversion_factor=conversion_factor - ) - - if cache_path is not None: - if is_ensemble: - self.__save_ensemble_profiles_to_cache(cache_path) - else: - self.__save_forecast_profiles_to_cache(cache_path, atm_type) - - #: Attributes ``Environment`` derives from a Forecast/Ensemble dataset that - #: are not recoverable from the extracted profiles alone, so they travel - #: with the cache entry to keep a cache hit indistinguishable from a fetch. - __CACHED_MODEL_METADATA = ( - "atmospheric_model_init_date", - "atmospheric_model_end_date", - "atmospheric_model_interval", - "atmospheric_model_init_lat", - "atmospheric_model_end_lat", - "atmospheric_model_init_lon", - "atmospheric_model_end_lon", - "lat_array", - "lon_array", - "lat_index", - "lon_index", - "geopotentials", - "wind_us", - "wind_vs", - "levels", - "temperatures", - "time_array", - "height", - ) - - def __collect_model_metadata(self): - """Snapshot the model metadata that must survive a cache round-trip.""" - return { - name: getattr(self, name) - for name in self.__CACHED_MODEL_METADATA - if getattr(self, name, None) is not None - } - - def __restore_model_metadata(self, metadata): - """Reinstate the model metadata recovered from a cache entry.""" - for name, value in (metadata or {}).items(): - if name in self.__CACHED_MODEL_METADATA: - setattr(self, name, value) - - def __apply_profiles_from_arrays( - self, height, pressure, temperature, wind_u, wind_v - ): - """Install forecast-style profile Functions from 1-D arrays.""" - wind_speed = calculate_wind_speed(wind_u, wind_v) - wind_heading = calculate_wind_heading(wind_u, wind_v) - wind_direction = convert_wind_heading_to_direction(wind_heading) - data_array = mask_and_clean_dataset( - pressure, - height, - temperature, - wind_u, - wind_v, - wind_heading, - wind_direction, - wind_speed, - ) - self.__set_pressure_function(data_array[:, (1, 0)]) - self.__set_barometric_height_function(data_array[:, (0, 1)]) - self.__set_temperature_function(data_array[:, (1, 2)]) - self.__set_wind_velocity_x_function(data_array[:, (1, 3)]) - self.__set_wind_velocity_y_function(data_array[:, (1, 4)]) - self.__set_wind_heading_function(data_array[:, (1, 5)]) - self.__set_wind_direction_function(data_array[:, (1, 6)]) - self.__set_wind_speed_function(data_array[:, (1, 7)]) - return data_array - - def __apply_cached_forecast_profiles(self, cache_path): - """Load Forecast/Reanalysis profiles from disk. Return True on success.""" - profiles = read_profile_netcdf(cache_path) - if profiles is None: - return False - self.__apply_profiles_from_arrays( - profiles["height"], - profiles["pressure"], - profiles["temperature"], - profiles["wind_u"], - profiles["wind_v"], - ) - self.elevation = profiles["elevation"] - self._max_expected_height = profiles["max_expected_height"] - self.__restore_model_metadata(profiles.get("metadata")) - return True - - @staticmethod - def __profile_column(function, column=1): - """Return one column of an array-backed Function, or None.""" - if not isinstance(function, Function) or not function.is_array_source(): - return None - source = np.asarray(function.source, dtype=float) - if source.ndim != 2 or source.shape[1] <= column: - return None - return source[:, column] - - def __save_forecast_profiles_to_cache(self, cache_path, kind="forecast"): - """Persist the active Forecast/Reanalysis profiles to ``cache_path``.""" - heights = self.__profile_column(self.pressure, column=0) - columns = { - "pressure": self.__profile_column(self.pressure), - "temperature": self.__profile_column(self.temperature), - "wind_u": self.__profile_column(self.wind_velocity_x), - "wind_v": self.__profile_column(self.wind_velocity_y), - } - # Every profile must be array-backed and share the pressure grid; - # constant (scalar) profiles carry nothing worth caching. - if heights is None or any( - column is None or column.shape != heights.shape - for column in columns.values() - ): - return - - write_profile_netcdf( - cache_path, - height=heights, - elevation=float(self.elevation), - max_expected_height=float( - getattr(self, "_max_expected_height", self.max_expected_height) - ), - kind=kind, - metadata=self.__collect_model_metadata(), - **columns, - ) - - def __apply_cached_ensemble_profiles(self, cache_path): - """Load Ensemble member profiles from disk. Return True on success.""" - profiles = read_ensemble_profile_netcdf(cache_path) - if profiles is None: - return False - - height = profiles["height_ensemble"] - temper = profiles["temperature_ensemble"] - wind_u = profiles["wind_u_ensemble"] - wind_v = profiles["wind_v_ensemble"] - - self.level_ensemble = profiles["levels"] - self.height_ensemble = height - self.temperature_ensemble = temper - self.wind_u_ensemble = wind_u - self.wind_v_ensemble = wind_v - self.wind_heading_ensemble = calculate_wind_heading(wind_u, wind_v) - self.wind_direction_ensemble = convert_wind_heading_to_direction( - self.wind_heading_ensemble - ) - self.wind_speed_ensemble = calculate_wind_speed(wind_u, wind_v) - self.num_ensemble_members = height.shape[0] - self.elevation = profiles["elevation"] - self._max_expected_height = profiles["max_expected_height"] - self.__restore_model_metadata(profiles.get("metadata")) - self.select_ensemble_member() - return True - - def __save_ensemble_profiles_to_cache(self, cache_path): - """Persist Ensemble member profiles to ``cache_path``.""" - if getattr(self, "height_ensemble", None) is None: - return - write_ensemble_profile_netcdf( - cache_path, - levels=self.level_ensemble, - height_ensemble=self.height_ensemble, - temperature_ensemble=self.temperature_ensemble, - wind_u_ensemble=self.wind_u_ensemble, - wind_v_ensemble=self.wind_v_ensemble, - elevation=float(self.elevation), - max_expected_height=float( - getattr(self, "_max_expected_height", self.max_expected_height) - ), - metadata=self.__collect_model_metadata(), - ) - # Atmospheric model processing methods def process_standard_atmosphere(self): @@ -1930,9 +1897,7 @@ def wind_heading_func(h): # TODO: create another custom reset for heading self._max_expected_height = max_expected_height - def process_windy_atmosphere( # pylint: disable=too-many-statements - self, model="ECMWF", no_cache=False - ): + def process_windy_atmosphere(self, model="ECMWF"): # pylint: disable=too-many-statements """Process data from Windy.com to retrieve atmospheric forecast data. Parameters @@ -1942,8 +1907,6 @@ def process_windy_atmosphere( # pylint: disable=too-many-statements ``ECMWF`` for the `ECMWF-HRES` model, ``GFS`` for the `GFS` model, ``ICON`` for the `ICON-Global` model or ``ICONEU`` for the `ICON-EU` model. - no_cache : bool, optional - If True, force a fresh download even when a JSON cache entry exists. Raises ------ @@ -1958,22 +1921,9 @@ def process_windy_atmosphere( # pylint: disable=too-many-statements "Valid options are 'ECMWF', 'GFS', 'ICON' or 'ICONEU'." ) - cache_path = cache_path_for( - build_atmosphere_cache_key( - "windy", - model, - self.latitude, - self.longitude, - self.datetime_date, - ), - ".json", + response = fetch_atmospheric_data_from_windy( + self.latitude, self.longitude, model ) - response = None if no_cache else load_json_cache(cache_path, kind="windy") - if response is None: - response = fetch_atmospheric_data_from_windy( - self.latitude, self.longitude, model - ) - save_json_cache(cache_path, response) # Determine time index from model time_array = np.array(response["data"]["hours"]) diff --git a/rocketpy/environment/tools.py b/rocketpy/environment/tools.py index c681d4d39..c2f1c4262 100644 --- a/rocketpy/environment/tools.py +++ b/rocketpy/environment/tools.py @@ -5,16 +5,29 @@ future to improve their performance and usability. """ +import contextlib +import hashlib +import json import logging import math +import os +import tempfile +import time import warnings from datetime import datetime +from pathlib import Path import netCDF4 import numpy as np +from platformdirs import user_cache_dir +from rocketpy.mathutils.function import Function from rocketpy.tools import bilinear_interpolation +# Forecasts saved on disk this many days ago are deleted when another one is +# saved. Reanalysis data never changes, so it is kept. +FORECAST_DAYS_KEPT = 7 + logger = logging.getLogger(__name__) @@ -697,6 +710,153 @@ def get_initial_date_from_time_array(time_array, units=None): return _to_datetime(netCDF4.num2date(time_array[0], units, calendar="gregorian")) +def get_model_run(dataset, time_name, datetime_date): + """Identify the model run that supplies the forecast for a given time. + + Forecast datasets that join several model runs, such as the "Best" time + series of the UCAR THREDDS server, carry ``reftime`` variables with the + reference time of the run each forecast time comes from. While a new run + is being published, some forecast times already come from it and others + still come from the previous one, so the run is read at the forecast time + closest to ``datetime_date``. The first and last forecast times are part + of the answer, so it also changes when the dataset covers other times. + + Parameters + ---------- + dataset : netCDF4.Dataset + Dataset opened from the forecast server. + time_name : str + Name of the time variable of the dataset. + datetime_date : datetime.datetime + Time the forecast is wanted for, in UTC. + + Returns + ------- + tuple or None + The address of the dataset, the reference time of the model run that + supplies ``datetime_date``, and the first and last forecast times of + the dataset. None if the model run cannot be identified: the dataset + does not carry reference times along its time variable, they cannot + be read, or ``datetime_date`` is outside the forecast times. + """ + variables = getattr(dataset, "variables", None) + if variables is None or datetime_date is None or time_name not in variables: + return None + time_array = variables[time_name] + reference_times = next( + ( + variable + for name, variable in variables.items() + if name.lower().startswith("reftime") + and variable.dimensions == time_array.dimensions + ), + None, + ) + if reference_times is None: + return None + try: + times = time_array[:] + wanted = netCDF4.date2num(datetime_date, time_array.units, calendar="gregorian") + if np.ma.is_masked(times) or not np.min(times) <= wanted <= np.max(times): + return None + times = np.asarray(times, dtype=float) + # Same choice as find_time_index: the closest time, the earlier on a tie + reference_time = reference_times[int(np.argmin(np.abs(times - wanted)))] + if np.ma.is_masked(reference_time) or not np.isfinite(reference_time): + return None + model_run = netCDF4.num2date(reference_time, reference_times.units) + except (TypeError, ValueError, OverflowError, OSError, RuntimeError): + return None + return dataset.filepath(), str(model_run), float(times[0]), float(times[-1]) + + +def atmosphere_cache_path(kind, request): + """Return the file where ``Environment.set_atmospheric_model(cache=True)`` + saves one request, in the cache folder of the system + (``~/.cache/rocketpy/atmosphere`` on Linux). ``kind`` is ``"forecast"`` + or ``"reanalysis"``.""" + name = hashlib.sha256(repr(request).encode("utf-8")).hexdigest()[:32] + return Path(user_cache_dir("rocketpy")) / "atmosphere" / f"{kind}_{name}.json" + + +def save_atmosphere(path, data): + """Save ``data`` as JSON in ``path``, then delete the forecasts saved more + than ``FORECAST_DAYS_KEPT`` days ago. Warns if it cannot be saved. + + The file is written under another name and then renamed, so another + process never reads half of it. + """ + try: + text = json.dumps(_to_json(data)) + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile( + "w", dir=path.parent, suffix=".tmp", delete=False, encoding="utf-8" + ) as file: + file.write(text) + os.replace(file.name, path) + except (OSError, TypeError, ValueError): + warnings.warn( + f"Could not save the atmospheric model in '{path.parent}'. It will " + "be downloaded again next time." + ) + return + oldest = time.time() - FORECAST_DAYS_KEPT * 24 * 3600 + for saved in path.parent.glob("forecast_*.json"): + with contextlib.suppress(OSError): + if saved.stat().st_mtime < oldest: + saved.unlink() + + +def load_atmosphere(path): + """Return the data saved in ``path``, or None if there is no such file or + it cannot be read.""" + try: + with open(path, encoding="utf-8") as file: + return _from_json(json.load(file)) + except (OSError, ValueError, KeyError, TypeError): + return None + + +def _to_json(value): + """Turn what the atmosphere processing sets into numbers, text and lists, + so that loading the file never runs code. Arrays, masked arrays, dates and + Functions defined by points are tagged to be rebuilt by ``_from_json``.""" + if isinstance(value, dict): + return {key: _to_json(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_to_json(item) for item in value] + if isinstance(value, Function): + if not isinstance(value.source, np.ndarray): + raise TypeError("Only Functions defined by points are saved.") + return {"__function__": _to_json(value.to_dict(allow_pickle=False))} + if isinstance(value, np.ma.MaskedArray): + return {"__masked__": value.data.tolist(), "mask": value.mask.tolist()} + if isinstance(value, np.ndarray): + return {"__array__": value.tolist()} + if isinstance(value, datetime): + return {"__datetime__": value.isoformat()} + if isinstance(value, np.generic): + return value.item() + return value + + +def _from_json(value): + """Rebuild what ``_to_json`` saved.""" + if isinstance(value, list): + return [_from_json(item) for item in value] + if not isinstance(value, dict): + return value + if "__function__" in value: + return Function.from_dict(_from_json(value["__function__"])) + if "__masked__" in value: + return np.ma.MaskedArray(value["__masked__"], mask=value["mask"]) + if "__array__" in value: + return np.array(value["__array__"]) + if "__datetime__" in value: + return datetime.fromisoformat(value["__datetime__"]) + return {key: _from_json(item) for key, item in value.items()} + + def get_final_date_from_time_array(time_array, units=None): """Returns a datetime object representing the last time in the time array. diff --git a/tests/conftest.py b/tests/conftest.py index 621ddc2a5..e4ec33e26 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,14 +8,16 @@ @pytest.fixture(autouse=True) -def isolate_atmosphere_cache(monkeypatch, tmp_path): - """Keep the atmosphere disk cache out of the developer's home directory. - - Without this, ``set_atmospheric_model`` would write to - ``~/.rocketpy_cache`` during the test run and later tests could silently - read profiles cached by an earlier one. - """ - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path / "rocketpy_cache")) +def forget_saved_forecasts(monkeypatch, tmp_path_factory): + """Start every test with no forecast kept in memory or saved on disk, so + that no test reuses what an earlier one downloaded and no test writes in + the cache folder of the user.""" + # pylint: disable=import-outside-toplevel + from rocketpy.environment import environment, tools + + environment._FORECASTS_IN_MEMORY.clear() + folder = str(tmp_path_factory.mktemp("rocketpy_cache")) + monkeypatch.setattr(tools, "user_cache_dir", lambda appname: folder) # Pytest configuration diff --git a/tests/unit/environment/test_atmosphere_cache.py b/tests/unit/environment/test_atmosphere_cache.py deleted file mode 100644 index a0b8bf250..000000000 --- a/tests/unit/environment/test_atmosphere_cache.py +++ /dev/null @@ -1,575 +0,0 @@ -"""Unit tests for atmosphere netCDF/JSON disk caching (#654).""" - -import time -import warnings -from datetime import datetime -from unittest.mock import MagicMock - -import netCDF4 -import numpy as np -import pytest - -from rocketpy import Environment -from rocketpy.environment import atmosphere_cache - - -def _write_minimal_profile_nc(path, elevation=1400.0): - """Create a tiny valid profile cache file for apply tests.""" - height = np.array([1400.0, 5000.0, 10000.0]) - pressure = np.array([85000.0, 54000.0, 26500.0]) - temperature = np.array([288.0, 255.0, 223.0]) - wind_u = np.array([1.0, 2.0, 3.0]) - wind_v = np.array([-1.0, 0.0, 1.0]) - assert atmosphere_cache.write_profile_netcdf( - path, - height=height, - pressure=pressure, - temperature=temperature, - wind_u=wind_u, - wind_v=wind_v, - elevation=elevation, - max_expected_height=10000.0, - kind="forecast", - ) - - -def test_cache_root_honors_rocketpy_cache_env(monkeypatch, tmp_path): - """``ROCKETPY_CACHE`` redirects the atmosphere cache root.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - assert atmosphere_cache.get_cache_root() == tmp_path - assert atmosphere_cache.get_atmosphere_cache_dir() == tmp_path / "atmosphere" - - -def test_profile_netcdf_roundtrip(monkeypatch, tmp_path): - """Write and read forecast profile netCDF through the cache helpers.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("forecast_test_key", ".nc") - _write_minimal_profile_nc(path) - loaded = atmosphere_cache.read_profile_netcdf(path) - assert loaded is not None - assert loaded["elevation"] == pytest.approx(1400.0) - np.testing.assert_allclose(loaded["height"], [1400.0, 5000.0, 10000.0]) - np.testing.assert_allclose(loaded["pressure"], [85000.0, 54000.0, 26500.0]) - - -def test_json_cache_roundtrip(monkeypatch, tmp_path): - """Windy-style JSON cache round-trips through disk.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("windy_test_key", ".json") - payload = {"data": {"hours": [1, 2, 3], "temp-surface": [288]}} - assert atmosphere_cache.save_json_cache(path, payload) - assert atmosphere_cache.load_json_cache(path) == payload - - -def test_forecast_shortcut_reuses_disk_cache(monkeypatch, tmp_path): - """Second Forecast shortcut call loads profiles from disk (no re-fetch).""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - fixture = "data/weather/SpaceportAmerica_2018_ERA-5.nc" - fetch_calls = [] - - def fake_fetch(): - fetch_calls.append(1) - return netCDF4.Dataset(fixture) - - env = Environment( - latitude=32.990254, - longitude=-106.974998, - elevation=1400, - datum="WGS84", - ) - env.set_date((2018, 10, 15, 12)) - env._Environment__atm_type_file_to_function_map["forecast"]["GFS"] = fake_fetch - - env.set_atmospheric_model( - type="Forecast", - file="GFS", - dictionary="ECMWF", - pressure_conversion_factor="hPa", - ) - assert len(fetch_calls) == 1 - pressure_first = env.pressure(env.elevation) - cached_files = list((tmp_path / "atmosphere").glob("*.nc")) - assert cached_files, "Expected a profile .nc cache file after first fetch" - - env2 = Environment( - latitude=32.990254, - longitude=-106.974998, - elevation=1400, - datum="WGS84", - ) - env2.set_date((2018, 10, 15, 12)) - env2._Environment__atm_type_file_to_function_map["forecast"]["GFS"] = fake_fetch - env2.set_atmospheric_model( - type="Forecast", - file="GFS", - dictionary="ECMWF", - pressure_conversion_factor="hPa", - ) - assert len(fetch_calls) == 1, "Second call should reuse disk cache" - assert env2.pressure(env2.elevation) == pytest.approx(pressure_first, rel=1e-6) - - -def test_forecast_no_cache_bypasses_disk(monkeypatch, tmp_path): - """``no_cache=True`` forces a re-fetch even when a cache file exists.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - fixture = "data/weather/SpaceportAmerica_2018_ERA-5.nc" - fetch_calls = [] - - def fake_fetch(): - fetch_calls.append(1) - return netCDF4.Dataset(fixture) - - env = Environment( - latitude=32.990254, - longitude=-106.974998, - elevation=1400, - datum="WGS84", - ) - env.set_date((2018, 10, 15, 12)) - env._Environment__atm_type_file_to_function_map["forecast"]["GFS"] = fake_fetch - - env.set_atmospheric_model( - type="Forecast", - file="GFS", - dictionary="ECMWF", - pressure_conversion_factor="hPa", - ) - env.set_atmospheric_model( - type="Forecast", - file="GFS", - dictionary="ECMWF", - pressure_conversion_factor="hPa", - no_cache=True, - ) - assert len(fetch_calls) == 2 - - -def test_windy_json_cache_hit(monkeypatch, tmp_path): - """Windy response is cached as JSON; second call skips the network.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - - # Minimal Windy payload matching __parse_windy_file expectations. - levels = [1000, 950, 925, 900, 850, 800, 700, 600, 500, 400, 300, 250, 200, 150] - payload = { - "header": {"elevation": 1234.0}, - "data": { - "hours": [1_540_000_000_000, 1_540_003_600_000], - }, - } - for level in levels: - # Geopotential heights increasing with altitude (decreasing pressure). - payload["data"][f"gh-{level}h"] = [ - float(2000 + (1000 - level) * 10), - float(2000 + (1000 - level) * 10), - ] - payload["data"][f"temp-{level}h"] = [280.0, 281.0] - payload["data"][f"wind_u-{level}h"] = [1.0, 1.5] - payload["data"][f"wind_v-{level}h"] = [-1.0, -0.5] - - fetch_mock = MagicMock(return_value=payload) - monkeypatch.setattr( - "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", - fetch_mock, - ) - - env = Environment(latitude=45.0, longitude=10.0, elevation=100) - env.set_date(datetime(2018, 10, 15, 12)) - env.set_atmospheric_model(type="Windy", file="ECMWF") - assert fetch_mock.call_count == 1 - assert list((tmp_path / "atmosphere").glob("*.json")) - - env2 = Environment(latitude=45.0, longitude=10.0, elevation=100) - env2.set_date(datetime(2018, 10, 15, 12)) - env2.set_atmospheric_model(type="Windy", file="ECMWF") - assert fetch_mock.call_count == 1 - - env3 = Environment(latitude=45.0, longitude=10.0, elevation=100) - env3.set_date(datetime(2018, 10, 15, 12)) - env3.set_atmospheric_model(type="Windy", file="ECMWF", no_cache=True) - assert fetch_mock.call_count == 2 - - -# --------------------------------------------------------------------------- -# Regression tests for the cache-hit / fresh-fetch parity contract -# --------------------------------------------------------------------------- - - -#: Attributes ``Environment`` derives from the dataset. A cache hit must -#: reproduce every one of them, otherwise ``info()`` and ``to_dict()`` break on -#: the second run of an otherwise identical script. -DERIVED_MODEL_ATTRIBUTES = [ - "atmospheric_model_init_date", - "atmospheric_model_end_date", - "atmospheric_model_interval", - "atmospheric_model_init_lat", - "atmospheric_model_end_lat", - "atmospheric_model_init_lon", - "atmospheric_model_end_lon", - "lat_array", - "lon_array", - "lat_index", - "lon_index", - "geopotentials", - "wind_us", - "wind_vs", - "levels", - "temperatures", - "time_array", - "height", -] - - -def _forecast_env(fetch): - """Build an Environment wired to ``fetch`` and load the Forecast model.""" - env = Environment( - latitude=32.990254, - longitude=-106.974998, - elevation=1400, - datum="WGS84", - ) - env.set_date((2018, 10, 15, 12)) - env._Environment__atm_type_file_to_function_map["forecast"]["GFS"] = fetch - env.set_atmospheric_model( - type="Forecast", - file="GFS", - dictionary="ECMWF", - pressure_conversion_factor="hPa", - ) - return env - - -def _counting_fetch(calls, fixture="data/weather/SpaceportAmerica_2018_ERA-5.nc"): - def fetch(): - calls.append(1) - return netCDF4.Dataset(fixture) - - return fetch - - -def test_cache_hit_restores_every_derived_attribute(monkeypatch, tmp_path): - """A cache hit must rebuild the same Environment a fresh fetch produces.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - calls = [] - fetch = _counting_fetch(calls) - - fresh = _forecast_env(fetch) - cached = _forecast_env(fetch) - assert len(calls) == 1, "second call should have been served from disk" - - for name in DERIVED_MODEL_ATTRIBUTES: - expected = getattr(fresh, name) - actual = getattr(cached, name, None) - assert actual is not None, f"'{name}' was lost on the cached path" - if isinstance(expected, datetime): - assert actual == expected, name - else: - np.testing.assert_allclose( - np.ma.filled(np.ma.asarray(actual, dtype=float), np.nan), - np.ma.filled(np.ma.asarray(expected, dtype=float), np.nan), - rtol=1e-10, - err_msg=name, - ) - - -def test_cache_hit_environment_can_print_info(monkeypatch, tmp_path): - """``info()`` used to raise AttributeError on the second (cached) run.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - calls = [] - fetch = _counting_fetch(calls) - - _forecast_env(fetch) - cached = _forecast_env(fetch) - - assert len(calls) == 1 - cached.info() # must not raise - - -def test_cache_hit_matches_fresh_profiles(monkeypatch, tmp_path): - """Profiles served from disk are numerically identical to a fresh fetch.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - calls = [] - fetch = _counting_fetch(calls) - - fresh = _forecast_env(fetch) - cached = _forecast_env(fetch) - - heights = np.linspace(fresh.elevation, fresh.max_expected_height, 25) - for name in ( - "pressure", - "temperature", - "wind_velocity_x", - "wind_velocity_y", - "wind_speed", - "wind_heading", - "wind_direction", - ): - np.testing.assert_allclose( - [getattr(cached, name)(h) for h in heights], - [getattr(fresh, name)(h) for h in heights], - rtol=1e-10, - atol=1e-10, - err_msg=name, - ) - - -def test_constant_wind_profile_does_not_break_caching(monkeypatch, tmp_path): - """Saving must tolerate scalar profiles instead of raising IndexError. - - ``set_atmospheric_model`` used to index every profile as a 2-D array while - only checking ``pressure``, so a constant wind blew up the cache write. - """ - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - env = Environment(latitude=0, longitude=0, elevation=0) - env._Environment__atm_type_file_to_function_map = { - "forecast": {"GFS": lambda: "fake-dataset"}, - "ensemble": {}, - } - env.process_forecast_reanalysis = lambda dataset, dictionary, conversion_factor: ( - None - ) - - env.set_atmospheric_model(type="Forecast", file="gfs") # must not raise - - assert not list((tmp_path / "atmosphere").glob("*.nc")), ( - "nothing worth caching should have been written" - ) - - -def test_cache_disabled_by_environment_variable(monkeypatch, tmp_path): - """``ROCKETPY_CACHE=0`` turns the disk cache off entirely.""" - monkeypatch.setenv("ROCKETPY_CACHE", "0") - assert atmosphere_cache.is_cache_enabled() is False - - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - assert atmosphere_cache.is_cache_enabled() is True - - -def test_disabled_cache_refetches_every_time(monkeypatch, tmp_path): - """With caching off, a repeated request hits the network again.""" - monkeypatch.setenv("ROCKETPY_CACHE", "off") - calls = [] - fetch = _counting_fetch(calls) - - _forecast_env(fetch) - _forecast_env(fetch) - - assert len(calls) == 2 - assert not list(tmp_path.rglob("*.nc")) - - -def test_expired_forecast_entry_is_refetched(monkeypatch, tmp_path): - """Forecast entries older than the TTL are discarded, not served.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - monkeypatch.setenv("ROCKETPY_CACHE_TTL", "3600") - calls = [] - fetch = _counting_fetch(calls) - - _forecast_env(fetch) - assert len(calls) == 1 - - # Pretend the entry was written two hours ago. The real clock has to be - # sampled before patching, or the stub would call itself. - two_hours_from_now = time.time() + 7200 - monkeypatch.setattr(atmosphere_cache.time, "time", lambda: two_hours_from_now) - _forecast_env(fetch) - assert len(calls) == 2, "a stale forecast must not be reused" - - -def test_zero_ttl_disables_expiry(monkeypatch): - """``ROCKETPY_CACHE_TTL=0`` keeps entries forever.""" - monkeypatch.setenv("ROCKETPY_CACHE_TTL", "0") - assert atmosphere_cache.is_entry_expired(0.0, "forecast") is False - - -def test_reanalysis_entries_never_expire(monkeypatch): - """Reanalysis data is immutable, so the TTL does not apply to it.""" - monkeypatch.setenv("ROCKETPY_CACHE_TTL", "1") - assert atmosphere_cache.is_entry_expired(0.0, "reanalysis") is False - assert atmosphere_cache.is_entry_expired(0.0, "forecast") is True - - -def test_different_dictionary_uses_a_separate_entry(monkeypatch, tmp_path): - """The same source decoded with another dictionary must not collide.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - calls = [] - fetch = _counting_fetch(calls) - - _forecast_env(fetch) - - env = Environment( - latitude=32.990254, longitude=-106.974998, elevation=1400, datum="WGS84" - ) - env.set_date((2018, 10, 15, 12)) - env._Environment__atm_type_file_to_function_map["forecast"]["GFS"] = fetch - env.set_atmospheric_model( - type="Forecast", - file="GFS", - dictionary="ECMWF_v0", - pressure_conversion_factor="hPa", - ) - - assert len(calls) == 2, "a different dictionary must miss the cache" - assert len(list((tmp_path / "atmosphere").glob("*.nc"))) == 2 - - -def test_corrupt_cache_file_falls_back_to_fetch(monkeypatch, tmp_path): - """A damaged cache file degrades to a re-fetch instead of raising.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - calls = [] - fetch = _counting_fetch(calls) - - _forecast_env(fetch) - cached_file = next((tmp_path / "atmosphere").glob("*.nc")) - cached_file.write_bytes(b"this is not a netCDF file") - - with pytest.warns(UserWarning): - _forecast_env(fetch) - - assert len(calls) == 2 - - -def test_clear_atmosphere_cache_removes_entries(monkeypatch, tmp_path): - """``clear_atmosphere_cache`` empties the cache directory.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("forecast_clear_me", ".nc") - _write_minimal_profile_nc(path) - assert path.is_file() - - assert atmosphere_cache.clear_atmosphere_cache() is True - assert not path.is_file() - # Clearing an already-absent cache is not an error. - assert atmosphere_cache.clear_atmosphere_cache() is True - - -def test_json_cache_respects_ttl(monkeypatch, tmp_path): - """Windy JSON entries expire like the netCDF ones.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - monkeypatch.setenv("ROCKETPY_CACHE_TTL", "3600") - path = atmosphere_cache.cache_path_for("windy_ttl", ".json") - payload = {"data": {"hours": [1, 2, 3]}} - - assert atmosphere_cache.save_json_cache(path, payload) - assert atmosphere_cache.load_json_cache(path) == payload - - two_hours_from_now = time.time() + 7200 - monkeypatch.setattr(atmosphere_cache.time, "time", lambda: two_hours_from_now) - assert atmosphere_cache.load_json_cache(path) is None - - -def test_mismatched_profiles_are_skipped_without_warning(monkeypatch, tmp_path): - """A scalar wind profile is skipped cleanly, not written and not warned about. - - The save path used to check only ``pressure`` before slicing all four - profiles as 2-D arrays, so a constant wind raised ``IndexError``. Guarding - only ``pressure`` is not enough either: ``np.asarray(None, dtype=float)`` - silently yields ``nan``, so a missing column would be persisted as a cache - entry full of NaN winds. Checking every column keeps the write from being - attempted at all, which is why this asserts on the absence of a warning and - not just of a file. - """ - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - env = Environment(latitude=0, longitude=0, elevation=0) - env.set_atmospheric_model( - type="custom_atmosphere", - pressure=[[0.0, 101325.0], [1000.0, 89875.0]], - temperature=[[0.0, 288.0], [1000.0, 281.0]], - wind_u=5, - wind_v=-3, - ) - assert env.pressure.is_array_source() - assert not env.wind_velocity_x.is_array_source() - - path = atmosphere_cache.cache_path_for("forecast_mismatched", ".nc") - with warnings.catch_warnings(): - warnings.simplefilter("error") - env._Environment__save_forecast_profiles_to_cache(path) - - assert not path.exists() - - -# --------------------------------------------------------------------------- -# The cache swallows unusable-file errors, and nothing else -# --------------------------------------------------------------------------- - - -def test_unexpected_error_while_opening_is_not_swallowed(monkeypatch, tmp_path): - """A defect inside the cache must surface, not look like a cache miss.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("forecast_boom", ".nc") - _write_minimal_profile_nc(path) - - def explode(*_args, **_kwargs): - raise ZeroDivisionError("a bug, not a damaged file") - - monkeypatch.setattr(atmosphere_cache.netCDF4, "Dataset", explode) - - with pytest.raises(ZeroDivisionError): - atmosphere_cache.read_profile_netcdf(path) - - -def test_unexpected_error_while_reading_is_not_swallowed(monkeypatch, tmp_path): - """Same contract for failures after the file has been opened.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("forecast_boom_read", ".nc") - _write_minimal_profile_nc(path) - - def explode(_dataset): - raise ZeroDivisionError("a bug, not a damaged file") - - monkeypatch.setattr(atmosphere_cache, "_read_metadata", explode) - - with pytest.raises(ZeroDivisionError): - atmosphere_cache.read_profile_netcdf(path) - - -@pytest.mark.parametrize( - "error", - [ - OSError("damaged file"), - RuntimeError("dataset is closed"), - ValueError("wrong length"), - TypeError("bad dtype"), - KeyError("missing variable"), - AttributeError("missing attribute"), - ], -) -def test_unusable_cache_file_degrades_to_a_miss(monkeypatch, tmp_path, error): - """Every way netCDF4 reports an unusable file must become a cache miss.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("forecast_unusable", ".nc") - _write_minimal_profile_nc(path) - - def explode(_dataset): - raise error - - monkeypatch.setattr(atmosphere_cache, "_read_metadata", explode) - - with pytest.warns(UserWarning): - assert atmosphere_cache.read_profile_netcdf(path) is None - - -def test_write_failure_degrades_to_no_cache_entry(monkeypatch, tmp_path): - """A failed write warns and reports False instead of raising.""" - monkeypatch.setenv("ROCKETPY_CACHE", str(tmp_path)) - path = atmosphere_cache.cache_path_for("forecast_writefail", ".nc") - - def explode(_dataset, _metadata): - raise OSError("disk full") - - monkeypatch.setattr(atmosphere_cache, "_write_metadata", explode) - - with pytest.warns(UserWarning): - written = atmosphere_cache.write_profile_netcdf( - path, - height=np.array([0.0, 1000.0]), - pressure=np.array([101325.0, 89875.0]), - temperature=np.array([288.0, 281.0]), - wind_u=np.array([1.0, 2.0]), - wind_v=np.array([0.0, 1.0]), - elevation=0.0, - max_expected_height=1000.0, - ) - - assert written is False - assert not path.exists() - assert not list(path.parent.glob("*.tmp")), "temporary file was left behind" diff --git a/tests/unit/environment/test_environment.py b/tests/unit/environment/test_environment.py index 61d6c3ff4..f2eeb2c10 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -1402,3 +1402,22 @@ def test_set_atmospheric_model_rejects_unknown_pressure_unit(example_plain_env): example_plain_env.set_atmospheric_model( type="Forecast", file="dummy", pressure_conversion_factor="parsecs" ) + + +@pytest.mark.parametrize(("file", "model"), [(None, "ECMWF"), ("GFS", "GFS")]) +def test_windy_uses_its_default_model_when_none_is_given( + example_plain_env, monkeypatch, file, model +): + asked = [] + + def fetch(latitude, longitude, model): # pylint: disable=unused-argument + asked.append(model) + raise RuntimeError("stop before any download") + + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", fetch + ) + + with pytest.raises(RuntimeError, match="stop before any download"): + example_plain_env.set_atmospheric_model(type="windy", file=file) + assert asked == [model] diff --git a/tests/unit/environment/test_forecast_reuse.py b/tests/unit/environment/test_forecast_reuse.py new file mode 100644 index 000000000..e7030caff --- /dev/null +++ b/tests/unit/environment/test_forecast_reuse.py @@ -0,0 +1,624 @@ +"""Reuse of a forecast already downloaded, in memory in the same Python +session and on disk with ``cache=True``. The forecast server is replaced by +small netCDF files shaped like the GFS forecast, read by the real processing, +so nothing here needs a network.""" + +import os +import time +from datetime import datetime + +import netCDF4 +import numpy as np +import pytest + +from rocketpy import Environment +from rocketpy.environment import environment as environment_module +from rocketpy.environment import tools +from rocketpy.environment.tools import ( + FORECAST_DAYS_KEPT, + atmosphere_cache_path, + get_model_run, + load_atmosphere, + save_atmosphere, +) + +UNITS = "Hour since 2026-01-01T00:00:00Z" +HOURS = (24, 30, 36, 42) +LAUNCH = (2026, 1, 2, 12) # 36 hours after the start of the time axis +LAUNCH_DATE = datetime(*LAUNCH) +SURFACE_HEIGHT = 1400.0 + + +FIELDS = ("time", "isobaric", "lat", "lon") + + +def _write_coordinates(data, runs, hours, masked_run): + """Write the times, the model run behind each of them and the grid.""" + for name, size in zip(FIELDS, (len(hours), 5, 3, 3)): + data.createDimension(name, size) + time = data.createVariable("time", "f8", ("time",)) + time.units = UNITS + time[:] = hours + if runs is not None: + reference_time = data.createVariable("reftime", "f8", ("time",)) + reference_time.units = UNITS + reference_time[:] = runs + if masked_run is not None: + reference_time[masked_run] = np.ma.masked + data.createVariable("lat", "f8", ("lat",))[:] = [34.0, 33.0, 32.0] + data.createVariable("lon", "f8", ("lon",))[:] = [252.0, 253.0, 254.0] + level = data.createVariable("isobaric", "f8", ("isobaric",)) + level.units = "Pa" + level[:] = [30000.0, 50000.0, 70000.0, 85000.0, 100000.0] + # Named by the AIGFS shortcut, whose forecast has no surface height + data.createVariable("LatLon_Projection", "i4") + + +def _write_fields(data, runs, hours): + """Write profiles that are the same over the grid. The temperature and + the wind depend on the model run, so two runs give different profiles.""" + shape = (len(hours), 5, 3, 3) + run = np.array([0] * len(hours) if runs is None else runs, dtype=float) + run = run[:, None, None, None] + + def field(name, values, shift=0.0): + values = np.array(values, dtype=float)[None, :, None, None] + variable = data.createVariable(name, "f8", FIELDS) + variable[:] = np.broadcast_to(values, shape) + shift + + field("Geopotential_height_isobaric", [9200, 5600, 3000, 1500, 100]) + field("Temperature_isobaric", [229, 253, 268, 278, 288], shift=run / 6) + field("u-component_of_wind_isobaric", [3, 2, 1, -1, -2]) + field("v-component_of_wind_isobaric", [12, 10, 8, 6, 4], shift=run / 6) + surface = data.createVariable( + "Geopotential_height_surface", "f8", FIELDS[:1] + FIELDS[2:] + ) + surface[:] = SURFACE_HEIGHT + + +def _write_forecast(path, runs, hours=HOURS, masked_run=None): + """Write a forecast with a few pressure levels around the launch site. + + ``runs`` holds the hour of the model run behind each forecast time, or is + None for a dataset that does not say. + """ + with netCDF4.Dataset(path, "w") as data: + _write_coordinates(data, runs, hours, masked_run) + _write_fields(data, runs, hours) + + +class _Server: + """Stands in for the forecast server: one address, whose dataset is + replaced when the server publishes something new.""" + + def __init__(self, folder, runs=(6, 6, 6, 6), **dataset): + self.path = str(folder / "Best.nc") + self.reachable = True + self.fetch_arguments = [] + self.datasets = [] + self.processed = 0 + self.publish(runs, **dataset) + + def publish(self, runs, **dataset): + _write_forecast(self.path, runs, **dataset) + + def fetch(self, **kwargs): + self.fetch_arguments.append(kwargs) + if not self.reachable: + raise RuntimeError("Unable to load latest weather data") + self.datasets.append(netCDF4.Dataset(self.path)) + return self.datasets[-1] + + def environment(self, **kwargs): + site = {"date": LAUNCH, "latitude": 32.99, "longitude": -106.97} + env = Environment(**{**site, **kwargs}) + env._Environment__atm_type_file_to_function_map = { + "forecast": {"GFS": self.fetch, "AIGFS": self.fetch}, + "ensemble": {}, + } + process = env.process_forecast_reanalysis + + def counted(*args, **kwargs): + self.processed += 1 + return process(*args, **kwargs) + + env.process_forecast_reanalysis = counted + return env + + def forecast(self, model="GFS", cache=False, **kwargs): + """An Environment with the forecast of the server already set.""" + env = self.environment(**kwargs) + env.set_atmospheric_model(type="Forecast", file=model, cache=cache) + return env + + +@pytest.fixture +def server(tmp_path): + return _Server(tmp_path) + + +class _FakeVariable: + units = UNITS + + def __init__(self, hours, dimensions=("time",)): + self._hours = np.array(hours, dtype=float) + self.dimensions = dimensions + + def __getitem__(self, index): + return self._hours[index] + + +class _FakeDataset: + """What identifying the model run needs from a dataset.""" + + def __init__(self, runs=None): + self.variables = {"time": _FakeVariable(HOURS)} + if runs is not None: + self.variables["reftime"] = _FakeVariable(runs) + + def filepath(self): + return "https://example.test/forecast/Best" + + +def test_model_run_is_the_one_behind_the_wanted_time(): + """While a new run is being published, the first forecast times already + come from it and the later ones still come from the previous run.""" + dataset = _FakeDataset(runs=(12, 12, 6, 6)) + address = "https://example.test/forecast/Best" + + assert get_model_run(dataset, "time", LAUNCH_DATE)[:2] == ( + address, + "2026-01-01 06:00:00", + ) + assert get_model_run(dataset, "time", datetime(2026, 1, 2, 0))[:2] == ( + address, + "2026-01-01 12:00:00", + ) + + +def test_model_run_comes_with_the_times_the_dataset_covers(): + dataset = _FakeDataset(runs=(6, 6, 6, 6)) + + assert get_model_run(dataset, "time", LAUNCH_DATE)[2:] == (24.0, 42.0) + + +def test_model_run_uses_the_reference_times_of_the_same_time_axis(): + dataset = _FakeDataset(runs=(6, 6, 6, 6)) + dataset.variables["reftime1"] = _FakeVariable((18, 18), dimensions=("time1",)) + + assert get_model_run(dataset, "time", LAUNCH_DATE)[1] == "2026-01-01 06:00:00" + + +@pytest.mark.parametrize( + ("dataset", "time_name", "date"), + [ + (_FakeDataset(runs=None), "time", LAUNCH_DATE), + (_FakeDataset(runs=(6, 6, 6, 6)), "another_time", LAUNCH_DATE), + (_FakeDataset(runs=(6, 6, 6, 6)), "time", None), + (_FakeDataset(runs=(6, 6, 6, 6)), "time", datetime(2026, 1, 1, 12)), + (_FakeDataset(runs=(6, 6, 6, 6)), "time", datetime(2026, 1, 3, 0)), + (_FakeDataset(runs=(6, 6, np.nan, 6)), "time", LAUNCH_DATE), + ("a/local/file.nc", "time", LAUNCH_DATE), + ], + ids=[ + "no reference times", + "no such time variable", + "no date", + "before the forecast", + "after the forecast", + "unreadable reference time", + "not a dataset", + ], +) +def test_model_run_is_unknown_when_the_dataset_does_not_say(dataset, time_name, date): + assert get_model_run(dataset, time_name, date) is None + + +def test_model_run_is_unknown_when_its_reference_time_is_masked(tmp_path): + path = str(tmp_path / "masked.nc") + _write_forecast(path, runs=(6, 6, 6, 6), masked_run=2) + + with netCDF4.Dataset(path) as dataset: + assert get_model_run(dataset, "time", LAUNCH_DATE) is None + assert get_model_run(dataset, "time", datetime(2026, 1, 2, 0)) is not None + + +def test_same_request_and_same_model_run_is_not_processed_again(server): + first = server.forecast() + second = server.forecast() + + assert server.processed == 1 + assert len(server.datasets) == 2, "the server is asked for its run each time" + assert not server.datasets[1].isopen() + assert second.temperature(2000) == first.temperature(2000) + + +def test_a_reused_forecast_leaves_the_environment_as_a_processed_one(server): + """Nothing the processing sets is missing or different after a reuse.""" + processed = server.forecast() + reused = server.forecast() + + assert vars(reused).keys() == vars(processed).keys() + assert reused.elevation == processed.elevation == pytest.approx(SURFACE_HEIGHT) + for name in ( + "pressure", + "temperature", + "wind_velocity_x", + "wind_velocity_y", + "wind_speed", + "wind_heading", + "wind_direction", + "density", + "speed_of_sound", + ): + assert getattr(reused, name)(2000) == getattr(processed, name)(2000), name + for name in ( + "atmospheric_model_init_date", + "atmospheric_model_end_date", + "atmospheric_model_interval", + "lat_index", + "lon_index", + "time_array", + "max_expected_height", + ): + assert getattr(reused, name) == getattr(processed, name), name + reused.prints.all() + + +def test_reused_results_are_copies(server): + first = server.forecast() + second = server.forecast() + second.temperature.set_discrete(0, 1000, 7) + third = server.forecast() + + assert second.temperature is not first.temperature + assert len(second.temperature.source) == 7 + assert len(first.temperature.source) == len(third.temperature.source) == 5 + + +def test_reused_wind_angles_do_not_read_another_environment(server): + """The wind heading and direction are read from their unwrapped versions, + which have to be the ones of the Environment itself.""" + first = server.forecast() + second = server.forecast() + direction, heading = second.wind_direction(2000), second.wind_heading(2000) + + for unwrapped in (first.wind_direction_unwrapped, first.wind_heading_unwrapped): + turned = np.array(unwrapped.get_source()) + turned[:, 1] += 90 + unwrapped.set_source(turned) + third = server.forecast() + + assert first.wind_direction(2000) == pytest.approx((direction + 90) % 360) + assert second.wind_direction(2000) == third.wind_direction(2000) == direction + assert second.wind_heading(2000) == third.wind_heading(2000) == heading + + +def test_a_new_model_run_is_downloaded_again(server): + first = server.forecast() + server.publish(runs=(12, 12, 12, 12)) + second = server.forecast() + third = server.forecast() + + assert server.processed == 2 + assert second.temperature(2000) == pytest.approx(first.temperature(2000) + 1) + assert third.temperature(2000) == second.temperature(2000) + + +def test_a_new_model_run_counts_once_it_reaches_the_launch_time(server): + """The launch is at the third forecast time. A new run that has only + replaced the first two changes nothing for it; once it replaces the third, + the forecast is downloaded again.""" + server.forecast() + server.publish(runs=(12, 12, 6, 6)) + server.forecast() + assert server.processed == 1 + + server.publish(runs=(12, 12, 12, 6)) + server.forecast() + assert server.processed == 2 + + +@pytest.mark.parametrize( + "other_request", + [{"latitude": 32.5}, {"longitude": -106.5}, {"date": (2026, 1, 2, 6)}], +) +def test_a_different_request_is_downloaded(server, other_request): + server.forecast() + server.forecast(**other_request) + + assert server.processed == 2 + + +def test_the_elevation_given_by_the_user_is_not_part_of_the_request(server): + """The model has a surface height, which replaces the elevation.""" + first = server.forecast(elevation=0) + second = server.forecast(elevation=500) + + assert server.processed == 1 + assert first.elevation == second.elevation == pytest.approx(SURFACE_HEIGHT) + + +def test_asking_twice_on_the_same_environment_processes_once(server): + env = server.forecast() + env.set_atmospheric_model(type="Forecast", file="GFS") + other = server.forecast(elevation=env.elevation) + + assert server.processed == 1 + assert vars(other).keys() == vars(env).keys() + other.prints.all() + + +def test_elevation_is_kept_when_the_model_has_no_surface_height(server): + first = server.forecast("AIGFS", elevation=120) + second = server.forecast("AIGFS", elevation=450) + + assert server.processed == 1 + assert (first.elevation, second.elevation) == (120, 450) + + +def test_a_launch_time_the_dataset_no_longer_covers_is_an_error(server): + """Same model run behind every time, but the forecast has moved on.""" + server.forecast() + server.publish(runs=(6, 6, 6, 6), hours=(42, 48, 54, 60)) + + with pytest.raises(ValueError, match="not available in the provided file"): + server.forecast() + + +def test_a_dataset_covering_other_times_is_downloaded_again(server): + """The run behind the launch time is the same, but the forecast now goes + further, which the Environment reports.""" + first = server.forecast() + server.publish(runs=(6, 6, 6, 6, 12), hours=(24, 30, 36, 42, 48)) + second = server.forecast() + + assert server.processed == 2 + assert first.atmospheric_model_end_date == datetime(2026, 1, 2, 18) + assert second.atmospheric_model_end_date == datetime(2026, 1, 3, 0) + + +@pytest.mark.parametrize("dataset", [{"runs": None}, {"masked_run": 2}]) +def test_a_model_run_that_cannot_be_identified_is_never_reused(tmp_path, dataset): + server = _Server(tmp_path, **{"runs": (6, 6, 6, 6), **dataset}) + server.forecast() + server.forecast() + + assert server.processed == 2 + assert not environment_module._FORECASTS_IN_MEMORY + + +def test_an_unreachable_server_fails_even_with_a_forecast_in_memory(server): + server.forecast() + server.reachable = False + env = server.environment() + + with pytest.raises(RuntimeError, match="Unable to load latest weather data"): + env.set_atmospheric_model(type="Forecast", file="GFS") + assert env.atmospheric_model_type == "Forecast" + assert not hasattr(env, "atmospheric_model_end_date") + + +def test_a_dataset_given_by_the_user_is_not_kept(server): + env = server.environment() + + env.set_atmospheric_model(type="Forecast", file=server.path, dictionary="GFS") + + assert server.processed == 1 + assert not environment_module._FORECASTS_IN_MEMORY + + +def test_only_the_latest_forecasts_are_kept(server, monkeypatch): + monkeypatch.setattr(environment_module, "_MAX_FORECASTS_IN_MEMORY", 2) + dates = [(2026, 1, 2, 0), (2026, 1, 2, 6), (2026, 1, 2, 12)] + + for date in dates: + server.forecast(date=date) + assert len(environment_module._FORECASTS_IN_MEMORY) == 2 + + server.forecast(date=dates[2]) + assert server.processed == 3, "the latest one is still in memory" + server.forecast(date=dates[0]) + assert server.processed == 4, "the oldest one was dropped" + + +# Saved on disk, with cache=True. The cache folder is a temporary one for each +# test, set in tests/conftest.py. + + +def _saved_files(): + folder = atmosphere_cache_path("forecast", None).parent + return sorted(folder.glob("*.json")) if folder.exists() else [] + + +def _new_session(): + """What a new Python session starts with: nothing kept in memory.""" + environment_module._FORECASTS_IN_MEMORY.clear() + + +def test_nothing_is_saved_on_disk_by_default(server): + """Without cache=True, a forecast is kept in memory only.""" + server.forecast() + + assert not _saved_files() + + +def test_a_saved_forecast_is_used_in_a_later_session(server): + """A forecast saved on disk is used again, with a warning, while the + server says its model run is still the latest one.""" + processed = server.forecast(cache=True) + _new_session() + + with pytest.warns(UserWarning, match="saved on disk.*still the latest"): + reused = server.forecast(cache=True) + + assert server.processed == 1 + assert len(_saved_files()) == 1 + assert vars(reused).keys() == vars(processed).keys() + assert reused.elevation == processed.elevation == pytest.approx(SURFACE_HEIGHT) + for name in ("pressure", "temperature", "wind_speed", "wind_direction"): + assert getattr(reused, name)(2000) == getattr(processed, name)(2000), name + assert reused.atmospheric_model_end_date == processed.atmospheric_model_end_date + + +def test_a_forecast_used_from_disk_is_then_kept_in_memory(server): + """Within the session that read it from disk, a forecast is reused from + memory, with no further warning.""" + server.forecast(cache=True) + _new_session() + with pytest.warns(UserWarning, match="saved on disk"): + server.forecast(cache=True) + + server.forecast(cache=True) + + assert server.processed == 1 + assert environment_module._FORECASTS_IN_MEMORY + + +def test_a_saved_forecast_is_replaced_by_a_new_model_run(server): + """A newer model run is downloaded and replaces the saved forecast.""" + first = server.forecast(cache=True) + _new_session() + server.publish((12, 12, 12, 12)) + + second = server.forecast(cache=True) + + assert server.processed == 2 + assert second.temperature(2000) != first.temperature(2000) + assert len(_saved_files()) == 1 + _new_session() + with pytest.warns(UserWarning, match="saved on disk"): + third = server.forecast(cache=True) + assert third.temperature(2000) == second.temperature(2000) + + +def test_a_saved_forecast_is_used_when_the_server_cannot_be_reached(server): + """Offline, the saved forecast is used with a warning, after a single + attempt to reach the server.""" + processed = server.forecast(cache=True) + _new_session() + server.reachable = False + + with pytest.warns(UserWarning, match="could not be reached"): + offline = server.forecast(cache=True) + + assert server.fetch_arguments[-1] == {"max_attempts": 1} + assert server.processed == 1 + assert offline.temperature(2000) == processed.temperature(2000) + + +def test_an_unreachable_server_still_fails_with_nothing_saved(server): + """With no saved forecast, the server is tried as many times as before + and the error is the same as without the cache.""" + server.reachable = False + + with pytest.raises(RuntimeError, match="Unable to load latest weather data"): + server.forecast(cache=True) + assert server.fetch_arguments == [{}] + + +def test_a_forecast_whose_model_run_is_unknown_is_not_saved(tmp_path): + """A forecast that cannot be checked against the server later is not + saved.""" + server = _Server(tmp_path, runs=None) + + server.forecast(cache=True) + + assert not _saved_files() + + +def test_a_damaged_saved_file_is_downloaded_again(server): + """A saved file that cannot be read counts as nothing saved.""" + server.forecast(cache=True) + _saved_files()[0].write_text("not a forecast", encoding="utf-8") + _new_session() + + server.forecast(cache=True) + + assert server.processed == 2 + assert load_atmosphere(_saved_files()[0]) is not None + + +def test_a_folder_that_cannot_be_written_only_warns(server, tmp_path, monkeypatch): + """The forecast is still set when it cannot be saved.""" + blocked = tmp_path / "a_file" + blocked.write_text("", encoding="utf-8") + monkeypatch.setattr(tools, "user_cache_dir", lambda appname: str(blocked)) + + with pytest.warns(UserWarning, match="Could not save the atmospheric model"): + env = server.forecast(cache=True) + + assert env.temperature(2000) > 0 + + +def test_old_forecasts_are_deleted_and_reanalysis_is_kept(): + """Forecasts saved more than the days kept are deleted when another one + is saved. Reanalysis data never changes, so it is kept.""" + long_ago = time.time() - (FORECAST_DAYS_KEPT + 1) * 24 * 3600 + old_forecast = atmosphere_cache_path("forecast", "old") + old_reanalysis = atmosphere_cache_path("reanalysis", "old") + for path in (old_forecast, old_reanalysis): + save_atmosphere(path, {}) + os.utime(path, (long_ago, long_ago)) + + new_forecast = atmosphere_cache_path("forecast", "new") + save_atmosphere(new_forecast, {}) + + assert not old_forecast.exists() + assert old_reanalysis.exists() + assert new_forecast.exists() + + +REANALYSIS_ADDRESS = "https://example.test/reanalysis.nc" + + +@pytest.fixture +def reanalysis(tmp_path, monkeypatch): + """A reanalysis at a web address, served from a local file. Returns the + list of the addresses opened.""" + path = str(tmp_path / "reanalysis.nc") + _write_forecast(path, runs=None) + opened = [] + real_dataset = netCDF4.Dataset + + def open_dataset(address, *args, **kwargs): + opened.append(address) + local = path if address == REANALYSIS_ADDRESS else address + return real_dataset(local, *args, **kwargs) + + monkeypatch.setattr(netCDF4, "Dataset", open_dataset) + return opened + + +def _reanalysis(file=REANALYSIS_ADDRESS, cache=True): + env = Environment(date=LAUNCH, latitude=32.99, longitude=-106.97) + env.set_atmospheric_model( + type="Reanalysis", + file=file, + dictionary="GFS", + pressure_conversion_factor="Pa", + cache=cache, + ) + return env + + +def test_a_reanalysis_from_a_web_address_is_saved_and_used_again(reanalysis): + """A saved reanalysis is used without contacting the server, with a + warning.""" + processed = _reanalysis() + + with pytest.warns(UserWarning, match="reanalysis saved on disk"): + reused = _reanalysis() + + assert reanalysis == [REANALYSIS_ADDRESS] + assert len(_saved_files()) == 1 + assert vars(reused).keys() == vars(processed).keys() + assert reused.temperature(2000) == processed.temperature(2000) + + +def test_a_reanalysis_from_a_local_file_is_not_saved(reanalysis, tmp_path): + """A local file is already on disk, so nothing is saved.""" + _reanalysis(file=str(tmp_path / "reanalysis.nc")) + + assert not _saved_files() + assert reanalysis == [str(tmp_path / "reanalysis.nc")]