Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,18 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
<!-- These are the changes that were not released yet, please add them correctly.
Attention: The newest changes should be on top -->

### 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
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/halcyon_flight_sim.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion docs/examples/valkyrie_flight_sim.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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()"
]
Expand Down
81 changes: 20 additions & 61 deletions docs/user/environment/1-atm-models/forecast.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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** <https://www.windy.com/>`_ can be used in RocketPy.
any location worldwide. RocketPy reads its forecasts through the official
`Windy Point Forecast API <https://api.windy.com/point-forecast/docs>`_, 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
Expand All @@ -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 <https://www.ecmwf.int/en/forecasts/datasets/open-data>`_.


GFS
^^^

Expand All @@ -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 <https://windy.app/blog/what-is-icon-weather-model-forecast.html>`_.
# 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
^^^^^^^
Expand All @@ -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::

Expand Down
142 changes: 103 additions & 39 deletions rocketpy/environment/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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://"))
Expand Down Expand Up @@ -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.

Expand All @@ -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"``,
Expand Down Expand Up @@ -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
-------
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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
(
Expand All @@ -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)])
Expand All @@ -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(
Expand All @@ -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,
Expand Down
Loading
Loading