diff --git a/CHANGELOG.md b/CHANGELOG.md index 2217004a9..812b6f3c3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,12 +30,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/). +### Breaking changes + +- `set_atmospheric_model(type="Windy")` needs a Windy Point Forecast API key, via `api_key` or the `WINDY_API_KEY` environment variable. It accepts only `GFS` (now the default, instead of `ECMWF`) and `ICONEU`: `ECMWF` and `ICON` raise `ValueError` and point to Open-Meteo. `fetch_atmospheric_data_from_windy` takes the key as its 4th argument. [#1254](https://github.com/RocketPy-Team/RocketPy/pull/1254) + ### Added ### Changed ### Fixed +- BUG: fetch Windy forecasts from the official Point Forecast API, which requires an API key [#1254](https://github.com/RocketPy-Team/RocketPy/pull/1254) + ## [v1.14.0] - 2026-11-29 ### Breaking changes diff --git a/docs/examples/halcyon_flight_sim.ipynb b/docs/examples/halcyon_flight_sim.ipynb index 503961448..ff3078507 100644 --- a/docs/examples/halcyon_flight_sim.ipynb +++ b/docs/examples/halcyon_flight_sim.ipynb @@ -245,7 +245,7 @@ " timezone=\"Portugal\",\n", ")\n", "\n", - "# env.set_atmospheric_model(type=\"Windy\", file=\"ECMWF\")\n", + "# env.set_atmospheric_model(type=\"open_meteo\", file=\"ecmwf_ifs025\")\n", "# env.max_expected_height = 4000\n", "# env.info()\n", "\n", diff --git a/docs/examples/valkyrie_flight_sim.ipynb b/docs/examples/valkyrie_flight_sim.ipynb index 5bb47894e..3c4cad5dc 100644 --- a/docs/examples/valkyrie_flight_sim.ipynb +++ b/docs/examples/valkyrie_flight_sim.ipynb @@ -148,7 +148,7 @@ " timezone=env_cfg[\"timezone\"],\n", ")\n", "\n", - "env.set_atmospheric_model(type=\"windy\", file=\"ICON\")\n", + "env.set_atmospheric_model(type=\"open_meteo\", file=\"icon_seamless\")\n", "env.max_expected_height = env_cfg[\"max_expected_height\"][\"value\"]\n", "env.info()" ] diff --git a/docs/user/environment/1-atm-models/forecast.rst b/docs/user/environment/1-atm-models/forecast.rst index d48e1908f..40db3fc4d 100644 --- a/docs/user/environment/1-atm-models/forecast.rst +++ b/docs/user/environment/1-atm-models/forecast.rst @@ -215,26 +215,31 @@ Using Windy Atmosphere ---------------------- **Windy.com** is a website that provides weather and atmospheric forecasts for -any location worldwide. -The same atmospheric predictions and data available on -`**windy.com** `_ can be used in RocketPy. +any location worldwide. RocketPy reads its forecasts through the official +`Windy Point Forecast API `_, which +requires an API key. Get one at https://api.windy.com/keys and set it in the +``WINDY_API_KEY`` environment variable, so it stays out of scripts and +notebooks. It can also be passed as ``api_key``. + +.. warning:: + + Windy's free **Testing** key returns randomly shuffled and slightly + modified data, meant only for development. Only a paid **Professional** + key returns the real forecast. RocketPy repeats Windy's warning when the + response carries one: do not fly simulations built on Testing data. The following models are accepted: -- **ECMWF-HRES** -- **GFS** -- **ICON-Global** +- **GFS** (the default) - **ICON-EU** (Europe only) +The Point Forecast API has no ECMWF model and no ICON-Global pressure-level +heights. For those, use :ref:`open_meteo` with ``file="ecmwf_ifs025"`` or +``file="icon_seamless"``. Let's see how to use Windy's data in RocketPy. First, we will set the location to EuRoC's launch area in Portugal. -.. note:: - - These examples require access to Windy's forecast service. If the service is - unavailable, try another forecast source such as :ref:`open_meteo`. - .. code-block:: python from datetime import datetime, timedelta @@ -248,29 +253,6 @@ to EuRoC's launch area in Portugal. ) -ECMWF -^^^^^ - -ECMWF (HRES) is a global, high-skill forecast model known for strong -medium-range performance. It is often a good choice for mission planning when -you need reliable synoptic-scale forecasts several days ahead. - -We can use the ``ECMWF`` model from Windy.com. - -.. code-block:: python - - env_windy.set_atmospheric_model(type="Windy", file="ECMWF") - env_windy_ecmwf = env_windy - env_windy_ecmwf.plots.atmospheric_model() - -.. note:: - - The ECMWF model is a global model with a resolution of 9 km. It is updated \ - every 12 hours and can forecast up to 10 days in advance. To learn more about \ - the ECMWF model, visit the \ - `ECMWF website `_. - - GFS ^^^ @@ -282,32 +264,10 @@ The ``GFS`` model is also available on Windy.com. This is the same model as described in the :ref:`global-forecast-system` section. .. code-block:: python - - env_windy.set_atmospheric_model(type="Windy", file="GFS") - env_windy_gfs = env_windy - env_windy_gfs.plots.atmospheric_model() - - -ICON -^^^^ - -ICON is DWD's global weather model, available in Windy for broad-scale -forecasting. It is useful as an independent global model source to cross-check -wind and temperature trends against GFS or ECMWF. - -The ICON model is a global weather forecasting model already available on Windy.com. -.. code-block:: python - - env_windy.set_atmospheric_model(type="Windy", file="ICON") - env_windy_icon = env_windy - env_windy_icon.plots.atmospheric_model() - -.. note:: - - The ICON model is a global model with a resolution of 13 km. It is updated \ - every 6 hours and can forecast up to 7 days in advance. For more information, \ - visit `here `_. + # Reads the key from the WINDY_API_KEY environment variable. + env_windy.set_atmospheric_model(type="Windy", file="GFS") + env_windy.plots.atmospheric_model() ICON-EU ^^^^^^^ @@ -321,8 +281,7 @@ The ICON-EU model is a regional weather forecasting model available on Windy.com .. code-block:: python env_windy.set_atmospheric_model(type="Windy", file="ICONEU") - env_windy_icon_eu = env_windy - env_windy_icon_eu.plots.atmospheric_model() + env_windy.plots.atmospheric_model() .. important:: diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index b76700d2d..898ba5f0a 100644 --- a/rocketpy/environment/environment.py +++ b/rocketpy/environment/environment.py @@ -33,6 +33,10 @@ from rocketpy.environment.fetchers.open_meteo_fetcher import ( OPEN_METEO_PRESSURE_LEVELS, ) +from rocketpy.environment.fetchers.windy_fetcher import ( + WINDY_MODELS, + WINDY_PRESSURE_LEVELS, +) from rocketpy.environment.tools import ( atmosphere_cache_path, calculate_wind_heading, @@ -111,6 +115,40 @@ ) +_WINDY_RETIRED_MODELS = { + "ecmwf": 'type="open_meteo", file="ecmwf_ifs025"', + "icon": 'type="open_meteo", file="icon_seamless"', +} +# Windy unit string -> (scale, offset) that converts it to SI. +_WINDY_UNITS_TO_SI = { + "K": (1, 0), + "°C": (1, 273.15), + "m": (1, 0), + "m*s-1": (1, 0), + "Pa": (1, 0), + "hPa": (100, 0), +} + + +def _windy_values(response, parameter, levels, time_index): + """Values of one Windy ``parameter`` at ``levels``, in SI units. + + Missing keys and ``null`` values come back masked. + """ + values = [] + for level in levels: + key = f"{parameter}-{level}" + if key not in response or response[key][time_index] is None: + values.append(np.nan) + continue + unit = response.get("units", {}).get(key) + if unit not in _WINDY_UNITS_TO_SI: + raise ValueError(f"Windy returned '{key}' in an unknown unit: '{unit}'.") + scale, offset = _WINDY_UNITS_TO_SI[unit] + values.append(scale * response[key][time_index] + offset) + return np.ma.masked_invalid(np.array(values, dtype=float)) + + 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://")) @@ -1454,6 +1492,7 @@ def set_atmospheric_model( # pylint: disable=too-many-statements username=None, password=None, cache=False, + api_key=None, ): """Define the atmospheric model for this Environment. @@ -1470,7 +1509,7 @@ def set_atmospheric_model( # pylint: disable=too-many-statements - ``"standard_atmosphere"`` and ``"custom_atmosphere"``: ignored. - ``"wyoming_sounding"``: URL of the sounding text page. - - ``"windy"``: one of ``"ECMWF"``, ``"GFS"``, ``"ICON"`` or + - ``"windy"``: ``"GFS"`` (the default when omitted) or ``"ICONEU"``. - ``"open_meteo"``: the Open-Meteo model to query, such as ``"best_match"`` (the default when omitted), ``"gfs_seamless"``, @@ -1586,6 +1625,10 @@ def set_atmospheric_model( # pylint: disable=too-many-statements 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. + api_key : string, optional + Windy Point Forecast API key, from https://api.windy.com/keys. Only + used when ``type`` is ``"windy"``. If None (the default), the value + is read from the ``WINDY_API_KEY`` environment variable. Returns ------- @@ -1635,7 +1678,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}) + **({} if file is None else {"model": file}), api_key=api_key ) case "open_meteo": self.process_open_meteo_atmosphere( @@ -1912,45 +1955,65 @@ def wind_heading_func(h): # TODO: create another custom reset for heading self._max_expected_height = max_expected_height - def process_windy_atmosphere(self, model="ECMWF"): # pylint: disable=too-many-statements - """Process data from Windy.com to retrieve atmospheric forecast data. + def process_windy_atmosphere(self, model="GFS", api_key=None): # pylint: disable=too-many-statements + """Process data from the Windy.com Point Forecast API to retrieve + atmospheric forecast data. Parameters ---------- model : string, optional - The atmospheric model to use. Default is ``ECMWF``. Options are: - ``ECMWF`` for the `ECMWF-HRES` model, ``GFS`` for the `GFS` model, - ``ICON`` for the `ICON-Global` model or ``ICONEU`` for the `ICON-EU` - model. + The atmospheric model to use. Default is ``GFS``. Options are + ``GFS`` for the `GFS` model or ``ICONEU`` for the `ICON-EU` model, + which covers only Europe. + api_key : string, optional + Windy Point Forecast API key, from https://api.windy.com/keys. + Defaults to the ``WINDY_API_KEY`` environment variable. Raises ------ ValueError - If ``model`` is not one of ``ECMWF``, ``GFS``, ``ICON`` or - ``ICONEU``. + If ``model`` is not ``GFS`` or ``ICONEU``, if no API key is given, + if Windy rejects the request, if it has no data for the launch + site or if the launch date is outside the forecast. """ - - if model.lower() not in ["ecmwf", "gfs", "icon", "iconeu"]: + model_key = model.lower() + if model_key in _WINDY_RETIRED_MODELS: + raise ValueError( + f"Windy's Point Forecast API does not provide the '{model}' " + "pressure-level forecast RocketPy needs. Use " + f"{_WINDY_RETIRED_MODELS[model_key]} instead." + ) + if model_key not in WINDY_MODELS: + raise ValueError( + f"Invalid model '{model}'. Valid options are 'GFS' or 'ICONEU'." + ) + api_key = api_key or os.environ.get("WINDY_API_KEY") + if not api_key: raise ValueError( - f"Invalid model '{model}'. " - "Valid options are 'ECMWF', 'GFS', 'ICON' or 'ICONEU'." + "Windy requires a Point Forecast API key. Pass it via " + "set_atmospheric_model(type='Windy', api_key=...) or set the " + "WINDY_API_KEY environment variable. Get one at " + "https://api.windy.com/keys." ) response = fetch_atmospheric_data_from_windy( - self.latitude, self.longitude, model + self.latitude, self.longitude, WINDY_MODELS[model_key], api_key ) # Determine time index from model - time_array = np.array(response["data"]["hours"]) + time_array = np.array(response["ts"]) time_units = "milliseconds since 1970-01-01 00:00:00" launch_time_in_units = netCDF4.date2num(self.datetime_date, time_units) + if not time_array[0] <= launch_time_in_units <= time_array[-1]: + first, last = (netCDF4.num2date(time_array[i], time_units) for i in (0, -1)) + raise ValueError( + f"The launch date {self.datetime_date} is outside the Windy " + f"'{model}' forecast, which runs from {first} to {last} UTC." + ) # Find the index of the closest time in time_array to the launch time time_index = (np.abs(time_array - launch_time_in_units)).argmin() - # Define available pressure levels - pressure_levels = np.array( - [1000, 950, 925, 900, 850, 800, 700, 600, 500, 400, 300, 250, 200, 150] - ) + pressure_levels = np.array(WINDY_PRESSURE_LEVELS) # Process geopotential height array ( @@ -1977,6 +2040,13 @@ def process_windy_atmosphere(self, model="ECMWF"): # pylint: disable=too-many-s wind_direction_array, wind_speed_array, ) + if len(data_array) < 2: + raise ValueError( + f"Windy returned no '{model}' forecast for latitude " + f"{self.latitude} and longitude {self.longitude}. Check that " + "the launch site is inside the model's domain (ICON-EU covers " + "only Europe)." + ) # Save atmospheric data self.__set_pressure_function(data_array[:, (1, 0)]) @@ -1989,10 +2059,15 @@ def process_windy_atmosphere(self, model="ECMWF"): # pylint: disable=too-many-s self.__set_wind_speed_function(data_array[:, (1, 7)]) # Save maximum expected height - self._max_expected_height = max(altitude_array[0], altitude_array[-1]) + self._max_expected_height = float(data_array[:, 1].max()) - # Get elevation data from file - self.elevation = float(response["header"]["elevation"]) + # The API returns no terrain elevation: take the height of the model's + # surface pressure in the profile just set. + surface_pressure = _windy_values(response, "pressure", ["surface"], time_index)[ + 0 + ] + if surface_pressure is not np.ma.masked: + self.elevation = float(self.barometric_height(surface_pressure)) # Compute info data self.atmospheric_model_init_date = get_initial_date_from_time_array( @@ -2019,26 +2094,15 @@ def process_windy_atmosphere(self, model="ECMWF"): # pylint: disable=too-many-s self.height = altitude_array def __parse_windy_file(self, response, time_index, pressure_levels): - geopotential_height_array = np.array( - [response["data"][f"gh-{pL}h"][time_index] for pL in pressure_levels] - ) + levels = [f"{level}h" for level in pressure_levels] + geopotential_height_array = _windy_values(response, "gh", levels, time_index) # Convert geopotential height to geometric altitude (ASL) altitude_array = geopotential_height_to_geometric_height( geopotential_height_array, self.earth_radius ) - - # Process temperature array (in Kelvin) - temperature_array = np.array( - [response["data"][f"temp-{pL}h"][time_index] for pL in pressure_levels] - ) - - # Process wind-u and wind-v array (in m/s) - wind_u_array = np.array( - [response["data"][f"wind_u-{pL}h"][time_index] for pL in pressure_levels] - ) - wind_v_array = np.array( - [response["data"][f"wind_v-{pL}h"][time_index] for pL in pressure_levels] - ) + temperature_array = _windy_values(response, "temp", levels, time_index) + wind_u_array = _windy_values(response, "wind_u", levels, time_index) + wind_v_array = _windy_values(response, "wind_v", levels, time_index) return ( geopotential_height_array, diff --git a/rocketpy/environment/fetchers/windy_fetcher.py b/rocketpy/environment/fetchers/windy_fetcher.py index ddb35bfb6..a7661cd6a 100644 --- a/rocketpy/environment/fetchers/windy_fetcher.py +++ b/rocketpy/environment/fetchers/windy_fetcher.py @@ -1,14 +1,57 @@ -"""Fetch weather data from Windy.com API.""" +"""Fetch weather data from the Windy.com Point Forecast API.""" + +import os +import warnings import requests from rocketpy.tools import exponential_backoff +WINDY_POINT_FORECAST_URL = "https://api.windy.com/api/point-forecast/v2" +WINDY_TIMEOUT_SECONDS = 30 +WINDY_PRESSURE_LEVELS = ( + 1000, + 950, + 925, + 900, + 850, + 800, + 700, + 600, + 500, + 400, + 300, + 200, + 150, +) +# Model names RocketPy accepts, case-insensitively, mapped to the API's names. +WINDY_MODELS = {"gfs": "gfs", "iconeu": "iconEu"} + + +@exponential_backoff(max_attempts=3, base_delay=2, max_delay=30) +def _post_point_forecast(body): + """Posts the request, retrying only network failures and server errors.""" + response = requests.post( + WINDY_POINT_FORECAST_URL, json=body, timeout=WINDY_TIMEOUT_SECONDS + ) + if response.status_code >= 500: + response.raise_for_status() + return response + + +def _error_message(response): + """The ``message`` of a Windy error body, or the raw text.""" + try: + body = response.json() + except ValueError: + return response.text + if isinstance(body, dict): + return body.get("message", response.text) + return response.text -@exponential_backoff(max_attempts=5, base_delay=2, max_delay=60) -def fetch_atmospheric_data_from_windy(lat, lon, model): - """Fetches atmospheric data from Windy.com API for a given latitude and - longitude, using a specific model. + +def fetch_atmospheric_data_from_windy(lat, lon, model, api_key=None): + """Fetches a pressure-level forecast from the Windy.com Point Forecast API. Parameters ---------- @@ -17,33 +60,75 @@ def fetch_atmospheric_data_from_windy(lat, lon, model): lon : float The longitude of the location. model : str - The atmospheric model to use. Options are: ecmwf, GFS, ICON or ICONEU. + The Windy model, ``"GFS"`` or ``"ICONEU"`` (case-insensitive). The + API's own spelling, such as ``"iconEu"``, is also accepted. + api_key : str, optional + A Windy Point Forecast API key, from https://api.windy.com/keys. + Defaults to the ``WINDY_API_KEY`` environment variable. Returns ------- dict - A dictionary containing the atmospheric data retrieved from the API. - """ - model = model.lower() - if model[-1] == "u": # case iconEu - model = "".join([model[:4], model[4].upper(), model[5:]]) - - url = ( - f"https://node.windy.com/forecast/meteogram/{model}/{lat}/{lon}/?step=undefined" - ) + The API response: ``ts`` (epoch milliseconds), ``units`` and one array + per ``{parameter}-{level}`` key, such as ``"temp-850h"``. + Raises + ------ + ValueError + If no API key is given, Windy rejects the request (e.g. an invalid + key), the model has no data for the location, or the response is not + a forecast. + RuntimeError + If Windy cannot be reached or keeps failing on its side. + """ + model = WINDY_MODELS.get(model.lower(), model) + api_key = api_key or os.environ.get("WINDY_API_KEY") + if not api_key: + raise ValueError( + "Windy requires a Point Forecast API key. Pass it via " + "set_atmospheric_model(type='Windy', api_key=...) or set the " + "WINDY_API_KEY environment variable. Get one at " + "https://api.windy.com/keys." + ) + body = { + "lat": lat, + "lon": lon, + "model": model, + "parameters": ["temp", "wind", "gh", "pressure"], + "levels": ["surface"] + [f"{level}h" for level in WINDY_PRESSURE_LEVELS], + "key": api_key, + } try: - response = requests.get(url).json() - if "data" not in response.keys(): # pragma: no cover - raise ValueError( - f"Could not get a valid response for '{model}' from Windy. " - "Check if the coordinates are set inside the model's domain." - ) - except requests.exceptions.RequestException as e: # pragma: no cover - if model == "iconEu": - raise ValueError( - "Could not get a valid response for Icon-EU from Windy. " - "Check if the coordinates are set inside Europe." - ) from e + response = _post_point_forecast(body) + except requests.exceptions.RequestException as e: + raise RuntimeError( + f"Could not get the '{model}' forecast from Windy: {e}" + ) from e - return response + if response.status_code == 204: + raise ValueError( + f"Windy has no '{model}' forecast for latitude {lat} and longitude " + f"{lon}. Check that the launch site is inside the model's domain " + "(ICON-EU covers only Europe)." + ) + if response.status_code != 200: + raise ValueError( + f"Windy rejected the '{model}' forecast request " + f"(HTTP {response.status_code}): {_error_message(response)}" + ) + try: + data = response.json() + except ValueError as e: + raise ValueError( + f"Windy answered the '{model}' forecast request with a body that " + f"is not JSON: {response.text[:200]}" + ) from e + if not isinstance(data, dict) or "ts" not in data or "units" not in data: + raise ValueError( + f"Windy answered the '{model}' forecast request without a " + f"forecast: {str(data)[:200]}" + ) + # Testing keys get shuffled, altered data, flagged only by this field. + if data.get("warning"): + warnings.warn(f"Windy: {data['warning']}", UserWarning) + return data diff --git a/tests/integration/environment/test_environment.py b/tests/integration/environment/test_environment.py index 368d13fd2..591d2d63a 100644 --- a/tests/integration/environment/test_environment.py +++ b/tests/integration/environment/test_environment.py @@ -1,3 +1,4 @@ +import os import time from datetime import date, datetime, timedelta, timezone from unittest.mock import patch @@ -165,15 +166,10 @@ def test_wind_plots_wrapping_direction(mock_show, example_plain_env): # pylint: @pytest.mark.slow -@pytest.mark.parametrize( - "model_name", - [ - "ECMWF", - "GFS", - "ICON", - "ICONEU", - ], +@pytest.mark.skipif( + not os.environ.get("WINDY_API_KEY"), reason="needs a Windy Point Forecast API key" ) +@pytest.mark.parametrize("model_name", ["GFS", "ICONEU"]) def test_windy_atmosphere(example_euroc_env, model_name): """Tests the Windy model in the environment object. The test ensures the pressure, temperature, and wind profiles are working and giving reasonable diff --git a/tests/unit/environment/test_environment.py b/tests/unit/environment/test_environment.py index 9dcc8ae8c..1cb3f99f4 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -1,6 +1,6 @@ import json import os -from datetime import datetime +from datetime import datetime, timedelta import numpy as np import numpy.testing as npt @@ -20,6 +20,7 @@ pressure_unit_to_factor, utm_to_geodesic, ) +from rocketpy.environment.fetchers.windy_fetcher import WINDY_PRESSURE_LEVELS from rocketpy.environment.weather_model_mapping import WeatherModelMapping from rocketpy.tools import geopotential_height_to_geometric_height @@ -1560,20 +1561,159 @@ def test_set_atmospheric_model_rejects_unknown_pressure_unit(example_plain_env): ) -@pytest.mark.parametrize(("file", "model"), [(None, "ECMWF"), ("GFS", "GFS")]) +@pytest.mark.parametrize( + ("file", "model"), [(None, "gfs"), ("GFS", "gfs"), ("ICONEU", "iconEu")] +) 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) + def fetch(latitude, longitude, model, api_key): # pylint: disable=unused-argument + asked.append((model, api_key)) raise RuntimeError("stop before any download") monkeypatch.setattr( "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", fetch ) + monkeypatch.setenv("WINDY_API_KEY", "from-env") with pytest.raises(RuntimeError, match="stop before any download"): example_plain_env.set_atmospheric_model(type="windy", file=file) - assert asked == [model] + assert asked == [(model, "from-env")] + + +def test_windy_without_an_api_key_raises_before_any_request( + example_plain_env, monkeypatch +): + monkeypatch.delenv("WINDY_API_KEY", raising=False) + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", + lambda *_: pytest.fail("no request should be made without a key"), + ) + + with pytest.raises(ValueError, match="WINDY_API_KEY"): + example_plain_env.set_atmospheric_model(type="windy", file="GFS") + + +@pytest.mark.parametrize("model", ["ECMWF", "ICON"]) +def test_windy_models_missing_from_the_official_api_point_to_open_meteo( + example_plain_env, model +): + with pytest.raises(ValueError, match="open_meteo"): + example_plain_env.set_atmospheric_model(type="windy", file=model, api_key="k") + + +def _windy_point_forecast(launch_ms, surface_pressure=99000.0, null_profile=False): + """A Point Forecast API response with an ISA-like profile at ``launch_ms``. + + The steps before and after the launch carry a 50 m/s wind, so a wrong time + index shows up in the wind. + """ + response = {"ts": [launch_ms - 3 * 3600e3, launch_ms, launch_ms + 3 * 3600e3]} + units = {"pressure-surface": "Pa"} + response["pressure-surface"] = [None, surface_pressure, None] + for level in WINDY_PRESSURE_LEVELS: + gh = 44330.8 * (1 - (level / 1013.25) ** 0.190263) + values = { + "gh": gh, + "temp": max(288.15 - 0.0065 * gh, 216.65), + "wind_u": 5.0, + "wind_v": -3.0, + } + for name, value in values.items(): + key = f"{name}-{level}h" + if null_profile: + response[key] = [None, None, None] + elif name.startswith("wind"): + response[key] = [50.0, value, 50.0] + else: + response[key] = [value, value, value] + units[key] = {"gh": "m", "temp": "K"}.get(name, "m*s-1") + response["units"] = units + return response + + +def test_windy_builds_the_profile_from_the_point_forecast_response( + example_euroc_env, monkeypatch +): + launch_ms = netCDF4.date2num( + example_euroc_env.datetime_date, "milliseconds since 1970-01-01 00:00:00" + ) + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", + lambda *_: _windy_point_forecast(launch_ms), + ) + + example_euroc_env.set_atmospheric_model(type="Windy", file="GFS", api_key="k") + + height_850 = example_euroc_env.barometric_height(85000) + assert height_850 == pytest.approx(1457, abs=5) + assert example_euroc_env.temperature(height_850) == pytest.approx(278.7, abs=0.5) + assert example_euroc_env.wind_velocity_x(1000) == pytest.approx(5.0) + assert example_euroc_env.wind_velocity_y(1000) == pytest.approx(-3.0) + # 990 hPa lies between the 1000 hPa (111 m) and 950 hPa (540 m) levels. + assert example_euroc_env.elevation == pytest.approx(197, abs=5) + + +def test_windy_without_data_at_the_launch_site_raises_value_error( + example_euroc_env, monkeypatch +): + launch_ms = netCDF4.date2num( + example_euroc_env.datetime_date, "milliseconds since 1970-01-01 00:00:00" + ) + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", + lambda *_: _windy_point_forecast(launch_ms, null_profile=True), + ) + + with pytest.warns(UserWarning), pytest.raises(ValueError, match="ICON-EU"): + example_euroc_env.set_atmospheric_model( + type="Windy", file="ICONEU", api_key="k" + ) + + +def _launch_ms(env): + return netCDF4.date2num(env.datetime_date, "milliseconds since 1970-01-01 00:00:00") + + +def test_windy_keeps_the_elevation_when_the_surface_pressure_is_null( + example_euroc_env, monkeypatch +): + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", + lambda *_: _windy_point_forecast( + _launch_ms(example_euroc_env), surface_pressure=None + ), + ) + + example_euroc_env.set_atmospheric_model(type="Windy", file="GFS", api_key="k") + + assert example_euroc_env.elevation == 100 + + +def test_windy_unknown_unit_raises_value_error(example_euroc_env, monkeypatch): + response = _windy_point_forecast(_launch_ms(example_euroc_env)) + response["units"]["temp-850h"] = "°F" + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", + lambda *_: response, + ) + + with pytest.raises(ValueError, match="unknown unit"): + example_euroc_env.set_atmospheric_model(type="Windy", file="GFS", api_key="k") + + +@pytest.mark.parametrize("days", [-2, 20]) +def test_windy_launch_outside_the_forecast_raises_value_error( + example_euroc_env, monkeypatch, days +): + response = _windy_point_forecast(_launch_ms(example_euroc_env)) + monkeypatch.setattr( + "rocketpy.environment.environment.fetch_atmospheric_data_from_windy", + lambda *_: response, + ) + example_euroc_env.set_date(example_euroc_env.datetime_date + timedelta(days=days)) + + with pytest.raises(ValueError, match="outside the Windy"): + example_euroc_env.set_atmospheric_model(type="Windy", file="GFS", api_key="k") diff --git a/tests/unit/environment/test_fetchers.py b/tests/unit/environment/test_fetchers.py index f2152f0d7..b10b08cb2 100644 --- a/tests/unit/environment/test_fetchers.py +++ b/tests/unit/environment/test_fetchers.py @@ -361,3 +361,147 @@ def test_fetch_open_elevation_error_payload_raises_runtime_error(monkeypatch): monkeypatch.setattr("rocketpy.tools.time.sleep", lambda _: None) with pytest.raises(RuntimeError, match="Open-Elevation"): fetchers.fetch_open_elevation(48.858844, 2.294351) + + +def test_windy_posts_the_key_and_levels_to_the_point_forecast_api(monkeypatch): + calls = [] + + def fake_post(url, json, timeout): # pylint: disable=redefined-outer-name + calls.append((url, json, timeout)) + return _FakeResponse({"ts": [0], "units": {}}) + + monkeypatch.setattr(fetchers.requests, "post", fake_post) + + response = fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "k") + + assert response == {"ts": [0], "units": {}} + url, body, _ = calls[0] + assert url == "https://api.windy.com/api/point-forecast/v2" + assert body["key"] == "k" + assert body["model"] == "gfs" + assert set(body["parameters"]) == {"temp", "wind", "gh", "pressure"} + assert "surface" in body["levels"] and "850h" in body["levels"] + + +def test_windy_rejected_key_raises_value_error_without_retrying(monkeypatch): + calls = [] + + def fake_post(*_, **__): + calls.append(1) + return _FakeResponse( + {"message": "Invalid API key", "error": "Bad Request"}, status_code=400 + ) + + monkeypatch.setattr(fetchers.requests, "post", fake_post) + monkeypatch.setattr("rocketpy.tools.time.sleep", lambda _: None) + + with pytest.raises(ValueError, match="Invalid API key"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "bad") + assert len(calls) == 1 + + +def test_windy_unreachable_raises_runtime_error(monkeypatch): + def fake_post(*_, **__): + raise fetchers.requests.exceptions.ConnectionError("down") + + monkeypatch.setattr(fetchers.requests, "post", fake_post) + monkeypatch.setattr("rocketpy.tools.time.sleep", lambda _: None) + + with pytest.raises(RuntimeError, match="Windy"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "k") + + +@pytest.mark.parametrize(("model", "sent"), [("GFS", "gfs"), ("ICONEU", "iconEu")]) +def test_windy_takes_the_key_from_the_environment_and_any_model_case( + monkeypatch, model, sent +): + bodies = [] + + def fake_post(_url, json, timeout): # pylint: disable=unused-argument + bodies.append(json) + return _FakeResponse({"ts": [0], "units": {}}) + + monkeypatch.setattr(fetchers.requests, "post", fake_post) + monkeypatch.setenv("WINDY_API_KEY", "from-env") + + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, model) + + assert bodies[0]["model"] == sent + assert bodies[0]["key"] == "from-env" + + +def test_windy_without_a_key_raises_before_posting(monkeypatch): + monkeypatch.delenv("WINDY_API_KEY", raising=False) + monkeypatch.setattr( + fetchers.requests, "post", lambda *_, **__: pytest.fail("posted") + ) + + with pytest.raises(ValueError, match="WINDY_API_KEY"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs") + + +def test_windy_no_content_points_to_the_model_domain(monkeypatch): + monkeypatch.setattr( + fetchers.requests, + "post", + lambda *_, **__: _FakeResponse(None, status_code=204), + ) + + with pytest.raises(ValueError, match="ICON-EU covers only Europe"): + fetchers.fetch_atmospheric_data_from_windy(-23.5, -46.6, "iconEu", "k") + + +def test_windy_server_errors_are_retried_then_raise_runtime_error(monkeypatch): + calls = [] + + def fake_post(*_, **__): + calls.append(1) + return _FakeResponse({}, status_code=503) + + monkeypatch.setattr(fetchers.requests, "post", fake_post) + monkeypatch.setattr("rocketpy.tools.time.sleep", lambda _: None) + + with pytest.raises(RuntimeError, match="Windy"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "k") + assert len(calls) == 3 + + +class _NotJsonResponse(_FakeResponse): + def json(self): + raise ValueError("Expecting value") + + +@pytest.mark.parametrize( + "response", + [ + _NotJsonResponse(None, text="captive portal"), + _FakeResponse({"message": "maintenance"}), + _FakeResponse(["not", "a", "forecast"]), + ], +) +def test_windy_success_without_a_forecast_raises_value_error(monkeypatch, response): + monkeypatch.setattr(fetchers.requests, "post", lambda *_, **__: response) + + with pytest.raises(ValueError, match="Windy answered"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "k") + + +def test_windy_error_body_that_is_not_an_object_keeps_the_text(monkeypatch): + monkeypatch.setattr( + fetchers.requests, + "post", + lambda *_, **__: _FakeResponse(["bad"], status_code=400, text="bad request"), + ) + + with pytest.raises(ValueError, match="HTTP 400.*bad request"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "k") + + +def test_windy_forwards_the_testing_key_warning(monkeypatch): + payload = {"ts": [0], "units": {}, "warning": "Data are randomly shuffled."} + monkeypatch.setattr( + fetchers.requests, "post", lambda *_, **__: _FakeResponse(payload) + ) + + with pytest.warns(UserWarning, match="randomly shuffled"): + fetchers.fetch_atmospheric_data_from_windy(39.39, -8.29, "gfs", "k")