diff --git a/docs/user/environment/1-atm-models/ensemble.rst b/docs/user/environment/1-atm-models/ensemble.rst index b7cdfd6be..28acf6fd1 100644 --- a/docs/user/environment/1-atm-models/ensemble.rst +++ b/docs/user/environment/1-atm-models/ensemble.rst @@ -30,9 +30,19 @@ is a two-column array: the first column is geometric height above sea level in meters, and the second column uses Pa for pressure, K for temperature and m/s for either wind component. -The pressure profiles determine a common isobaric grid. Temperature and wind -are interpolated onto that grid, then written to a GEFS-compatible NetCDF file. -Every pressure profile must overlap the others and decrease with height. +The pressure profiles determine a common isobaric grid, and temperature and +wind are interpolated onto that grid. Every pressure profile must overlap the +others and decrease with height. + +The profiles are not tied to a date. The Environment does not need one, and +the ensemble stays the same if the launch date is changed later. + +.. note:: + + Every profile is cut to the pressure range shared by all of them, and below + that range the value at its bottom is used. Start all profiles at the same + pressure, at or below the ground level of the launch site, so the values + near the ground are the ones you gave. .. code-block:: python @@ -41,15 +51,14 @@ Every pressure profile must overlap the others and decrease with height. from rocketpy import Environment env = Environment( - date=(2026, 9, 1, 12), latitude=32.990254, longitude=-106.974998, elevation=1400, ) pressure = np.array([85000, 70000, 50000]) # Pa - height_0 = np.array([1500, 3000, 5500]) # m ASL - height_1 = np.array([1550, 3100, 5650]) # m ASL + height_0 = np.array([1400, 3000, 5500]) # m ASL + height_1 = np.array([1400, 3100, 5650]) # m ASL profiles = [ { @@ -66,21 +75,29 @@ Every pressure profile must overlap the others and decrease with height. }, ] - ensemble_file = env.create_ensemble(profiles, "my_ensemble.nc") + env.create_ensemble(profiles) -The method activates member 0 after writing the file. Select another member -with the same method used for forecast ensembles: +The method activates member 0. Select another member with the same method used +for forecast ensembles: .. code-block:: python env.select_ensemble_member(1) -Another Environment can load the returned file with the ``GEFS`` mapping: +By default the ensemble is kept in memory and no file is written. To use it +again later, give a file name. RocketPy then also saves the ensemble as a +GEFS-compatible NetCDF file and returns its path: + +.. code-block:: python + + ensemble_file = env.create_ensemble(profiles, "my_ensemble.nc") + +Another Environment, with any launch date or none, can load that file with the +``GEFS`` mapping: .. code-block:: python saved_env = Environment( - date=(2026, 9, 1, 12), latitude=32.990254, longitude=-106.974998, elevation=1400, diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index 8ac6f4033..e77ce721a 100644 --- a/rocketpy/environment/environment.py +++ b/rocketpy/environment/environment.py @@ -5,6 +5,7 @@ import logging import os import re +import uuid import warnings from collections.abc import Mapping from collections import namedtuple @@ -71,6 +72,10 @@ geopotential_height_to_geometric_height, ) +# Written in the datasets of Environment.create_ensemble. It tells the loader +# that the ensemble comes from profiles given by the user, which have no date. +_USER_DEFINED_ENSEMBLE_SOURCE = "RocketPy Environment.create_ensemble" + logger = logging.getLogger(__name__) @@ -172,22 +177,25 @@ class Environment: Environment.atmospheric_model_file : string Address of the file used for the atmospheric model being used. Only defined for ``wyoming_sounding``, ``windy``, ``forecast``, - ``reanalysis``, ``ensemble`` + ``reanalysis``, ``ensemble``. An empty string for an ensemble created + from profiles with :meth:`Environment.create_ensemble` and kept only + in memory. Environment.atmospheric_model_dict : dictionary Dictionary used to properly interpret ``netCDF`` and ``OPeNDAP`` files. Only defined for ``forecast``, ``reanalysis``, ``ensemble``. Environment.atmospheric_model_init_date : datetime Datetime object instance of first available date in ``netCDF`` and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or - ``Ensemble``. + ``Ensemble``. ``None`` for an ensemble created from profiles, which + has no date. Environment.atmospheric_model_end_date : datetime Datetime object instance of last available date in ``netCDF`` and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or - ``Ensemble``. + ``Ensemble``. ``None`` for an ensemble created from profiles. Environment.atmospheric_model_interval : int Hour step between weather condition used in ``netCDF`` and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or - ``Ensemble``. + ``Ensemble``. ``0`` for an ensemble created from profiles. Environment.atmospheric_model_init_lat : float Latitude of vertex just before the launch site in ``netCDF`` and ``OPeNDAP`` files when using ``Forecast``, ``Reanalysis`` or @@ -859,11 +867,11 @@ def set_date(self, date, timezone="UTC"): # Update atmospheric conditions if atmosphere type is Forecast, # Reanalysis or Ensemble - if hasattr(self, "atmospheric_model_type") and self.atmospheric_model_type in [ - "Forecast", - "Reanalysis", - "Ensemble", - ]: + if ( + hasattr(self, "atmospheric_model_type") + and self.atmospheric_model_type in ["Forecast", "Reanalysis", "Ensemble"] + and not getattr(self, "_ensemble_from_profiles", False) + ): self.set_atmospheric_model( type=self.atmospheric_model_type, file=self.atmospheric_model_file, @@ -898,11 +906,11 @@ def set_location(self, latitude, longitude): # Update atmospheric conditions if atmosphere type is Forecast, # Reanalysis or Ensemble - if hasattr(self, "atmospheric_model_type") and self.atmospheric_model_type in [ - "Forecast", - "Reanalysis", - "Ensemble", - ]: + if ( + hasattr(self, "atmospheric_model_type") + and self.atmospheric_model_type in ["Forecast", "Reanalysis", "Ensemble"] + and not getattr(self, "_ensemble_from_profiles", False) + ): self.set_atmospheric_model( type=self.atmospheric_model_type, file=self.atmospheric_model_file, @@ -1410,6 +1418,7 @@ def set_atmospheric_model( # pylint: disable=too-many-statements """ # Save atmospheric model type self.atmospheric_model_type = type + self._ensemble_from_profiles = False type = type.lower() match type: @@ -3277,9 +3286,10 @@ def _create_ensemble_time_coordinate(self, dataset): time = dataset.createVariable("time", "f8", ("time",)) time.long_name = "profile valid time" time.standard_name = "time" - time.units = ( - f"hours since {self.datetime_date.strftime('%Y-%m-%d %H:%M:%S')} UTC" - ) + # The profiles have no date of their own and the loader does not check + # this one. The launch date is used when the Environment has one. + reference = self.datetime_date or datetime(1970, 1, 1) + time.units = f"hours since {reference.strftime('%Y-%m-%d %H:%M:%S')} UTC" time.calendar = "gregorian" time.axis = "T" time[:] = [0] @@ -3398,43 +3408,43 @@ def _create_ensemble_data_variables( variable.coordinates = "time ens lev lat lon" variable[:] = np.broadcast_to(values[None, :, :, None, None], data_shape) - def _write_ensemble_file( - self, file_path, pressure_levels, geopotential_heights, member_values + def _fill_ensemble_dataset( + self, dataset, pressure_levels, geopotential_heights, member_values ): - """Write prepared ensemble data to a GEFS-compatible NetCDF file.""" - with netCDF4.Dataset(file_path, "w", format="NETCDF4") as dataset: - dataset.Conventions = "CF-1.8" - dataset.title = "RocketPy user-defined atmospheric ensemble" - dataset.source = "RocketPy Environment.create_ensemble" - dataset.history = ( - f"Created {datetime.now(tz=pytz.UTC).isoformat()} by RocketPy" - ) - dataset.comment = ( - "Profiles are spatially constant across the 2 x 2 grid " - "surrounding the launch coordinates." - ) - dataset.launch_latitude = self.latitude - dataset.launch_longitude = self.longitude + """Write prepared ensemble data to an open GEFS-compatible dataset.""" + dataset.Conventions = "CF-1.8" + dataset.title = "RocketPy user-defined atmospheric ensemble" + dataset.source = _USER_DEFINED_ENSEMBLE_SOURCE + dataset.history = f"Created {datetime.now(tz=pytz.UTC).isoformat()} by RocketPy" + dataset.comment = ( + "Profiles are spatially constant across the 2 x 2 grid " + "surrounding the launch coordinates." + ) + dataset.launch_latitude = self.latitude + dataset.launch_longitude = self.longitude - data_shape = self._create_ensemble_coordinates( - dataset, len(geopotential_heights), pressure_levels - ) - self._create_ensemble_data_variables( - dataset, data_shape, geopotential_heights, member_values - ) + data_shape = self._create_ensemble_coordinates( + dataset, len(geopotential_heights), pressure_levels + ) + self._create_ensemble_data_variables( + dataset, data_shape, geopotential_heights, member_values + ) def create_ensemble( self, profiles, - file_name="custom_ensemble.nc", + file_name=None, pressure_levels=None, overwrite=False, ): """Create and activate an ensemble from user-defined profiles. - RocketPy writes the profiles with GEFS-compatible variable names. - Another Environment can load the returned file by passing - ``type="Ensemble"`` and ``dictionary="GEFS"`` to + The profiles are not tied to a date, so the Environment does not need + one and the ensemble stays the same when the launch date changes. By + default nothing is written to disk. Pass ``file_name`` to also save + the ensemble: RocketPy writes the profiles with GEFS-compatible + variable names, and any other Environment, whatever its date, can load + the file by passing ``type="Ensemble"`` and ``dictionary="GEFS"`` to :meth:`Environment.set_atmospheric_model`. Parameters @@ -3447,19 +3457,26 @@ def create_ensemble( Pa for pressure, K for temperature and m/s for either wind component. Array-backed :class:`rocketpy.Function` objects are also accepted. Pressure must decrease strictly with increasing height. + Every profile is cut to the pressure range shared by all of them, + and below that range the value at its bottom is used. Start all + profiles at the same pressure, at or below the ground level of the + launch site, so the values near the ground are the ones you gave. file_name : str or os.PathLike, optional - Path of the NetCDF file to create. The ``.nc`` suffix is appended - when omitted. Default is ``"custom_ensemble.nc"``. + Path of a NetCDF file to save the ensemble in. The ``.nc`` suffix + is appended when omitted. Default is ``None``, which keeps the + ensemble in memory and writes no file. pressure_levels : array-like, optional Common pressure levels in Pa. By default, the union of sampled pressure levels inside the range shared by every member is used. overwrite : bool, optional - Whether an existing file may be replaced. Default is ``False``. + Whether an existing file may be replaced. Only used when + ``file_name`` is given. Default is ``False``. Returns ------- - str - Absolute path of the created NetCDF file. + str or None + Absolute path of the created NetCDF file, or None when no file was + asked for. Raises ------ @@ -3470,14 +3487,13 @@ def create_ensemble( missing, profiles are invalid, or the members have no usable common pressure range. FileExistsError - If the output exists and ``overwrite`` is ``False``. + If ``file_name`` exists and ``overwrite`` is ``False``. Notes ----- - The first member is activated after the file is created. Use + The first member is activated. Use :meth:`Environment.select_ensemble_member` to activate another member. """ - self.__validate_datetime() members = self._prepare_ensemble_profiles(profiles) pressure_levels = self._prepare_ensemble_pressure_levels( members, pressure_levels @@ -3485,11 +3501,33 @@ def create_ensemble( geopotential_heights, member_values = self._interpolate_ensemble_profiles( members, pressure_levels ) - file_path = self._prepare_ensemble_file_path(file_name, overwrite) - self._write_ensemble_file( - file_path, pressure_levels, geopotential_heights, member_values - ) + ensemble = (pressure_levels, geopotential_heights, member_values) + + if file_name is None: + # A dataset that only exists in memory: nothing is written to disk. + # The name is unique so two such datasets never share one. + dataset = netCDF4.Dataset( + f"rocketpy_ensemble_{uuid.uuid4().hex}.nc", + "w", + format="NETCDF4", + diskless=True, + persist=False, + ) + try: + self._fill_ensemble_dataset(dataset, *ensemble) + self.set_atmospheric_model( + type="Ensemble", file=dataset, dictionary="GEFS" + ) + finally: + if dataset.isopen(): + dataset.close() + # There is no file to load the ensemble from again + self.atmospheric_model_file = str() + return None + file_path = self._prepare_ensemble_file_path(file_name, overwrite) + with netCDF4.Dataset(file_path, "w", format="NETCDF4") as dataset: + self._fill_ensemble_dataset(dataset, *ensemble) self.set_atmospheric_model(type="Ensemble", file=file_path, dictionary="GEFS") logger.info("Atmospheric ensemble saved at '%s'.", file_path) return file_path @@ -3561,15 +3599,24 @@ class for some dictionary examples. or if required geopotential/geopotential-height, temperature, wind-u, or wind-v variables cannot be read from the dataset. """ - # Check if date, lat and lon are known - self.__validate_datetime() - # Read weather file if isinstance(file, str): data = netCDF4.Dataset(file) else: data = file + # Profiles given by the user have no date, so the Environment does not + # need one and the time written in their dataset is not checked. + from_profiles = getattr(data, "source", None) == _USER_DEFINED_ENSEMBLE_SOURCE + self._ensemble_from_profiles = from_profiles + if not from_profiles: + try: + self.__validate_datetime() + except ValueError: + if isinstance(file, str): + data.close() + raise + dictionary = self.__resolve_dictionary_for_dataset(dictionary, data) # Get time, latitude and longitude data from file @@ -3599,7 +3646,10 @@ class for some dictionary examples. target_lat = self.latitude # Find time, latitude and longitude indexes - time_index = find_time_index(self.datetime_date, time_array) + if from_profiles: + time_index = 0 + else: + time_index = find_time_index(self.datetime_date, time_array) lon, lon_index = find_longitude_index(target_lon, lon_array) _, lat_index = find_latitude_index(target_lat, lat_array) @@ -3771,9 +3821,18 @@ class for some dictionary examples. ) # Compute info data - self.atmospheric_model_init_date = get_initial_date_from_time_array(time_array) - self.atmospheric_model_end_date = get_final_date_from_time_array(time_array) - self.atmospheric_model_interval = get_interval_date_from_time_array(time_array) + if from_profiles: + self.atmospheric_model_init_date = None + self.atmospheric_model_end_date = None + self.atmospheric_model_interval = 0 + else: + self.atmospheric_model_init_date = get_initial_date_from_time_array( + time_array + ) + self.atmospheric_model_end_date = get_final_date_from_time_array(time_array) + self.atmospheric_model_interval = get_interval_date_from_time_array( + time_array + ) self.atmospheric_model_init_lat = float(lat_array[0]) self.atmospheric_model_end_lat = float(lat_array[len(lat_array) - 1]) self.atmospheric_model_init_lon = float(lon_array[0]) @@ -4325,6 +4384,7 @@ def to_dict(self, **kwargs): "wind_speed_ensemble": getattr(self, "wind_speed_ensemble", None), "num_ensemble_members": getattr(self, "num_ensemble_members", None), "ensemble_member": getattr(self, "ensemble_member", None), + "ensemble_from_profiles": getattr(self, "_ensemble_from_profiles", False), } if kwargs.get("include_outputs", False): @@ -4403,6 +4463,7 @@ def from_dict(cls, data): # pylint: disable=too-many-statements env.wind_speed_ensemble = data["wind_speed_ensemble"] env.num_ensemble_members = data["num_ensemble_members"] env.ensemble_member = data.get("ensemble_member", 0) or 0 + env._ensemble_from_profiles = data.get("ensemble_from_profiles", False) env.__reset_barometric_height_function() env.calculate_density_profile() diff --git a/rocketpy/prints/environment_prints.py b/rocketpy/prints/environment_prints.py index 8ab847ac2..2325e0d56 100644 --- a/rocketpy/prints/environment_prints.py +++ b/rocketpy/prints/environment_prints.py @@ -117,15 +117,18 @@ def atmospheric_model_details(self): init_date = self.environment.atmospheric_model_init_date end_date = self.environment.atmospheric_model_end_date interval = self.environment.atmospheric_model_interval - print(f"{model_type} Time Period: from {init_date} to {end_date} utc") - print(f"{model_type} Hour Interval: {interval} hrs") - # Determine latitude and longitude range - init_lat = self.environment.atmospheric_model_init_lat - end_lat = self.environment.atmospheric_model_end_lat - init_lon = self.environment.atmospheric_model_init_lon - end_lon = self.environment.atmospheric_model_end_lon - print(f"{model_type} Latitude Range: From {init_lat}° to {end_lat}°") - print(f"{model_type} Longitude Range: From {init_lon}° to {end_lon}°") + # An ensemble created from profiles has no time period and no + # model grid, so neither is printed + if init_date is not None: + print(f"{model_type} Time Period: from {init_date} to {end_date} utc") + print(f"{model_type} Hour Interval: {interval} hrs") + # Determine latitude and longitude range + init_lat = self.environment.atmospheric_model_init_lat + end_lat = self.environment.atmospheric_model_end_lat + init_lon = self.environment.atmospheric_model_init_lon + end_lon = self.environment.atmospheric_model_end_lon + print(f"{model_type} Latitude Range: From {init_lat}° to {end_lat}°") + print(f"{model_type} Longitude Range: From {init_lon}° to {end_lon}°") if normalized_type in ["ensemble", "open_meteo_ensemble"]: print( f"Number of Ensemble Members: {self.environment.num_ensemble_members}" diff --git a/tests/unit/environment/test_environment.py b/tests/unit/environment/test_environment.py index 61d6c3ff4..8a5519884 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -148,6 +148,157 @@ def test_create_ensemble_does_not_overwrite_by_default(tmp_path): env.create_ensemble(_user_defined_ensemble_profiles(), file_name=file_path) +def test_create_ensemble_writes_no_file_by_default(tmp_path, monkeypatch): + """The ensemble is kept in memory, so running the same call again works + and the working folder is left as it was.""" + monkeypatch.chdir(tmp_path) + (tmp_path / "user_file.nc").write_text("not an ensemble") + env = Environment(date=(2025, 6, 1, 12), latitude=32.99, longitude=-106.97) + + first = env.create_ensemble(_user_defined_ensemble_profiles()) + second = env.create_ensemble(_user_defined_ensemble_profiles()) + + assert first is None and second is None + assert [file.name for file in tmp_path.iterdir()] == ["user_file.nc"] + assert (tmp_path / "user_file.nc").read_text() == "not an ensemble" + assert env.atmospheric_model_type == "Ensemble" + assert env.atmospheric_model_file == "" + assert env.num_ensemble_members == 2 + env.select_ensemble_member(1) + assert env.temperature(1100) == pytest.approx(283) + assert env.wind_velocity_x(1100) == pytest.approx(5) + + +@pytest.mark.parametrize("save", [False, True]) +def test_create_ensemble_does_not_need_a_launch_date(tmp_path, save): + """The profiles have no date, so neither does the Environment need one.""" + env = Environment(latitude=32.99, longitude=-106.97) + file_name = tmp_path / "no_date.nc" if save else None + + env.create_ensemble(_user_defined_ensemble_profiles(), file_name=file_name) + + assert env.num_ensemble_members == 2 + assert env.wind_velocity_x(1000) == pytest.approx(2) + + +@pytest.mark.parametrize("date", [(2025, 6, 1, 13), (2031, 1, 5, 3), None]) +def test_create_ensemble_file_loads_for_any_launch_date(tmp_path, date): + """A saved ensemble is not tied to the date it was created with.""" + source_env = Environment(date=(2025, 6, 1, 12), latitude=32.99, longitude=-106.97) + file_path = source_env.create_ensemble( + _user_defined_ensemble_profiles(), file_name=tmp_path / "any_date.nc" + ) + loaded_env = Environment(date=date, latitude=32.99, longitude=-106.97) + + loaded_env.set_atmospheric_model(type="Ensemble", file=file_path, dictionary="GEFS") + loaded_env.select_ensemble_member(1) + + assert loaded_env.temperature(1100) == pytest.approx(283) + assert loaded_env.wind_velocity_y(1100) == pytest.approx(-5) + + +def test_ensemble_file_from_elsewhere_still_checks_the_launch_date(tmp_path): + """Only the ensembles created from profiles are free of a date.""" + source_env = Environment(date=(2025, 6, 1, 12), latitude=32.99, longitude=-106.97) + file_path = source_env.create_ensemble( + _user_defined_ensemble_profiles(), file_name=tmp_path / "forecast.nc" + ) + with netCDF4.Dataset(file_path, "a") as dataset: + dataset.source = "A weather service" + + later = Environment(date=(2025, 6, 1, 13), latitude=32.99, longitude=-106.97) + with pytest.raises(ValueError, match="not available in the provided file"): + later.set_atmospheric_model(type="Ensemble", file=file_path, dictionary="GEFS") + + no_date = Environment(latitude=32.99, longitude=-106.97) + with pytest.raises(ValueError, match="specify the launch date"): + no_date.set_atmospheric_model( + type="Ensemble", file=file_path, dictionary="GEFS" + ) + + +def test_ensemble_file_is_closed_when_the_launch_date_is_missing(tmp_path, monkeypatch): + """A file that needs a launch date is closed again when none is set.""" + # Arrange + source_env = Environment(date=(2025, 6, 1, 12), latitude=32.99, longitude=-106.97) + file_path = source_env.create_ensemble( + _user_defined_ensemble_profiles(), file_name=tmp_path / "forecast.nc" + ) + with netCDF4.Dataset(file_path, "a") as dataset: + dataset.source = "A weather service" + opened = [] + real_dataset = netCDF4.Dataset + + def open_and_keep(*args, **kwargs): + dataset = real_dataset(*args, **kwargs) + opened.append(dataset) + return dataset + + monkeypatch.setattr(netCDF4, "Dataset", open_and_keep) + no_date = Environment(latitude=32.99, longitude=-106.97) + + # Act + with pytest.raises(ValueError, match="specify the launch date"): + no_date.set_atmospheric_model( + type="Ensemble", file=str(file_path), dictionary="GEFS" + ) + + # Assert + assert opened and not any(dataset.isopen() for dataset in opened) + + +def test_ensemble_from_profiles_stays_when_the_date_or_place_change(): + """The ensemble and the selected member are kept when the launch date or + place is changed.""" + # Arrange + env = Environment(latitude=32.99, longitude=-106.97) + env.create_ensemble(_user_defined_ensemble_profiles()) + env.select_ensemble_member(1) + + # Act + env.set_date((2030, 3, 4, 5)) + env.set_location(-21.96, -47.48) + + # Assert + assert env.num_ensemble_members == 2 + assert env.ensemble_member == 1 + assert env.wind_velocity_x(1100) == pytest.approx(5) + + +def test_ensemble_from_profiles_stays_after_saving_and_loading(): + """An ensemble created from profiles is kept when the Environment is saved + and loaded, and still needs no date.""" + # Arrange + env = Environment(latitude=32.99, longitude=-106.97) + env.create_ensemble(_user_defined_ensemble_profiles()) + + # Act + loaded = Environment.from_dict(env.to_dict()) + loaded.set_date((2030, 3, 4, 5)) + + # Assert + assert loaded.num_ensemble_members == 2 + assert loaded.wind_velocity_x(1000) == pytest.approx(2) + + +def test_ensemble_from_profiles_is_printed_without_a_time_period(capsys): + """The prints of an ensemble created from profiles leave out the time + period and the model grid, which it does not have.""" + # Arrange + env = Environment(latitude=32.99, longitude=-106.97) + env.create_ensemble(_user_defined_ensemble_profiles()) + + # Act + env.prints.all() + + # Assert + printed = capsys.readouterr().out + assert "Time Period" not in printed + assert "Latitude Range" not in printed + assert "Longitude Range" not in printed + assert "Number of Ensemble Members: 2" in printed + + def test_create_ensemble_accepts_array_functions_and_explicit_levels(tmp_path): """Accept array-backed Functions and sort explicit pressure levels.""" # Arrange