From d0db347a467659af763033c2585d9fb44f302940 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Fri, 20 Nov 2026 14:11:20 -0300 Subject: [PATCH 1/6] ENH: create custom ensembles without a file and without a date - `Environment.create_ensemble` keeps the ensemble in memory by default. A file is only written when `file_name` is given. - An ensemble created from profiles has no date: the Environment does not need one, and a saved ensemble loads for any launch date. Ensemble files from elsewhere still check the launch date. - `set_date` and `set_location` leave such an ensemble as it is, and the prints skip its time period. Co-Authored-By: Claude Fable 5.2 --- rocketpy/environment/environment.py | 164 ++++++++++++++------- rocketpy/prints/environment_prints.py | 6 +- tests/unit/environment/test_environment.py | 108 ++++++++++++++ 3 files changed, 219 insertions(+), 59 deletions(-) diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index 8ac6f4033..1ff95d6bd 100644 --- a/rocketpy/environment/environment.py +++ b/rocketpy/environment/environment.py @@ -71,6 +71,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__) @@ -859,11 +863,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 +902,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 +1414,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 +3282,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 +3404,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 +3453,24 @@ 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. + Below the lowest height of a profile its lowest value is used, so + start the profiles at or below the ground level of the launch site. 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 +3481,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 +3495,32 @@ 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 + dataset = netCDF4.Dataset( + "rocketpy_ensemble_in_memory.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 @@ -3562,14 +3593,19 @@ class for some dictionary examples. 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: + self.__validate_datetime() + dictionary = self.__resolve_dictionary_for_dataset(dictionary, data) # Get time, latitude and longitude data from file @@ -3599,7 +3635,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 +3810,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 +4373,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 +4452,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..8f609c516 100644 --- a/rocketpy/prints/environment_prints.py +++ b/rocketpy/prints/environment_prints.py @@ -117,8 +117,10 @@ 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") + # An ensemble created from profiles has no time period + 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 diff --git a/tests/unit/environment/test_environment.py b/tests/unit/environment/test_environment.py index 61d6c3ff4..60faad62b 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -148,6 +148,114 @@ 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 / "rocketpy_ensemble_in_memory.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()] == [ + "rocketpy_ensemble_in_memory.nc" + ] + assert (tmp_path / "rocketpy_ensemble_in_memory.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_from_profiles_stays_when_the_date_or_place_change(): + env = Environment(latitude=32.99, longitude=-106.97) + env.create_ensemble(_user_defined_ensemble_profiles()) + env.select_ensemble_member(1) + + env.set_date((2030, 3, 4, 5)) + env.set_location(-21.96, -47.48) + + 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(): + env = Environment(latitude=32.99, longitude=-106.97) + env.create_ensemble(_user_defined_ensemble_profiles()) + + loaded = Environment.from_dict(env.to_dict()) + loaded.set_date((2030, 3, 4, 5)) + + 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): + env = Environment(latitude=32.99, longitude=-106.97) + env.create_ensemble(_user_defined_ensemble_profiles()) + + env.prints.all() + + printed = capsys.readouterr().out + assert "Time Period" 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 From 6aef2607075954ca02b3a16e24e3289428521253 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Fri, 20 Nov 2026 14:11:20 -0300 Subject: [PATCH 2/6] DOC: update the custom ensemble guide Co-Authored-By: Claude Fable 5.2 --- .../environment/1-atm-models/ensemble.rst | 38 +++++++++++++------ 1 file changed, 27 insertions(+), 11 deletions(-) diff --git a/docs/user/environment/1-atm-models/ensemble.rst b/docs/user/environment/1-atm-models/ensemble.rst index b7cdfd6be..e958059f0 100644 --- a/docs/user/environment/1-atm-models/ensemble.rst +++ b/docs/user/environment/1-atm-models/ensemble.rst @@ -30,9 +30,18 @@ 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:: + + Below the lowest height of a profile, its lowest value is used. Start the + profiles 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 +50,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 +74,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, From 043f256632d08786feb3da198f99dc995a6e1012 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 21 Nov 2026 21:33:09 -0300 Subject: [PATCH 3/6] BUG: give each in-memory ensemble dataset its own name Co-Authored-By: Claude Opus 5.5 --- rocketpy/environment/environment.py | 6 ++++-- tests/unit/environment/test_environment.py | 10 +++------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index 1ff95d6bd..68066159f 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 @@ -3498,9 +3499,10 @@ def create_ensemble( ensemble = (pressure_levels, geopotential_heights, member_values) if file_name is None: - # A dataset that only exists in memory: nothing is written to disk + # 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( - "rocketpy_ensemble_in_memory.nc", + f"rocketpy_ensemble_{uuid.uuid4().hex}.nc", "w", format="NETCDF4", diskless=True, diff --git a/tests/unit/environment/test_environment.py b/tests/unit/environment/test_environment.py index 60faad62b..cd6d9381b 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -152,19 +152,15 @@ 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 / "rocketpy_ensemble_in_memory.nc").write_text("not an ensemble") + (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()] == [ - "rocketpy_ensemble_in_memory.nc" - ] - assert (tmp_path / "rocketpy_ensemble_in_memory.nc").read_text() == ( - "not an ensemble" - ) + 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 From 942313cfaaaf4b0d9266058168f99c6b3130af16 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 21 Nov 2026 21:33:09 -0300 Subject: [PATCH 4/6] BUG: close the ensemble file when the launch date is missing Co-Authored-By: Claude Opus 5.5 --- rocketpy/environment/environment.py | 8 ++++-- tests/unit/environment/test_environment.py | 30 ++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index 68066159f..a47804b71 100644 --- a/rocketpy/environment/environment.py +++ b/rocketpy/environment/environment.py @@ -3594,7 +3594,6 @@ 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 # Read weather file if isinstance(file, str): data = netCDF4.Dataset(file) @@ -3606,7 +3605,12 @@ class for some dictionary examples. from_profiles = getattr(data, "source", None) == _USER_DEFINED_ENSEMBLE_SOURCE self._ensemble_from_profiles = from_profiles if not from_profiles: - self.__validate_datetime() + try: + self.__validate_datetime() + except ValueError: + if isinstance(file, str): + data.close() + raise dictionary = self.__resolve_dictionary_for_dataset(dictionary, data) diff --git a/tests/unit/environment/test_environment.py b/tests/unit/environment/test_environment.py index cd6d9381b..7504f7f9e 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -217,6 +217,36 @@ def test_ensemble_file_from_elsewhere_still_checks_the_launch_date(tmp_path): ) +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(): env = Environment(latitude=32.99, longitude=-106.97) env.create_ensemble(_user_defined_ensemble_profiles()) From f3a5796481d494e3f5edcdb3e41cc5d1d7e01743 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 21 Nov 2026 21:33:09 -0300 Subject: [PATCH 5/6] DOC: describe the pressure range and the attributes of profile ensembles Co-Authored-By: Claude Opus 5.5 --- docs/user/environment/1-atm-models/ensemble.rst | 5 +++-- rocketpy/environment/environment.py | 17 +++++++++++------ 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/user/environment/1-atm-models/ensemble.rst b/docs/user/environment/1-atm-models/ensemble.rst index e958059f0..28acf6fd1 100644 --- a/docs/user/environment/1-atm-models/ensemble.rst +++ b/docs/user/environment/1-atm-models/ensemble.rst @@ -39,8 +39,9 @@ the ensemble stays the same if the launch date is changed later. .. note:: - Below the lowest height of a profile, its lowest value is used. Start the - profiles at or below the ground level of the launch site, so the values + 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 diff --git a/rocketpy/environment/environment.py b/rocketpy/environment/environment.py index a47804b71..e77ce721a 100644 --- a/rocketpy/environment/environment.py +++ b/rocketpy/environment/environment.py @@ -177,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 @@ -3454,8 +3457,10 @@ 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. - Below the lowest height of a profile its lowest value is used, so - start the profiles at or below the ground level of the launch site. + 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 a NetCDF file to save the ensemble in. The ``.nc`` suffix is appended when omitted. Default is ``None``, which keeps the From bc527133d77ea9d2fdb9b3b2ca613d4556f247a5 Mon Sep 17 00:00:00 2001 From: MateusStano Date: Sat, 21 Nov 2026 21:33:09 -0300 Subject: [PATCH 6/6] ENH: leave the model grid out of the prints of profile ensembles Also add docstrings and Arrange/Act/Assert comments to the profile ensemble tests. Co-Authored-By: Claude Opus 5.5 --- rocketpy/prints/environment_prints.py | 17 +++++++++-------- tests/unit/environment/test_environment.py | 17 +++++++++++++++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/rocketpy/prints/environment_prints.py b/rocketpy/prints/environment_prints.py index 8f609c516..2325e0d56 100644 --- a/rocketpy/prints/environment_prints.py +++ b/rocketpy/prints/environment_prints.py @@ -117,17 +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 - # An ensemble created from profiles has no time period + # 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}°") + # 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 7504f7f9e..8a5519884 100644 --- a/tests/unit/environment/test_environment.py +++ b/tests/unit/environment/test_environment.py @@ -248,37 +248,54 @@ def open_and_keep(*args, **kwargs): 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