From a6ccbab7c3d39e752b1b50a329ba3a00d5ffd7f0 Mon Sep 17 00:00:00 2001 From: David Rundus <114828622+rundvd@users.noreply.github.com> Date: Sat, 26 Sep 2026 01:00:08 +0000 Subject: [PATCH 01/11] BUG: fix inverted and wrong factors in the units conversion table Each UNITS_CONVERSION_DICT entry is the number of that unit in one base unit (1 m = 1e3 mm). Six entries did not follow that: deg, grad, mg and g were inverted, ft/s^2 used the inverse of ft/s, and atm was 1.01325e-5 instead of 1/101325. convert_units(np.pi, "rad", "deg") returned 0.0548. Add a table-driven test that checks every non-temperature unit against its exact SI definition in both directions. --- rocketpy/units.py | 12 +++++----- tests/unit/test_units.py | 50 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 6 deletions(-) diff --git a/rocketpy/units.py b/rocketpy/units.py index b8e4c199c..f044c2782 100644 --- a/rocketpy/units.py +++ b/rocketpy/units.py @@ -25,14 +25,14 @@ # Units of acceleration. Meter per square second "m/s^2" is the base unit. "m/s^2": 1, "gs": 1 / 9.80665, - "ft/s^2": 1 / 3.2808399, + "ft/s^2": 1 / 0.3048, # Units of pressure. Pascal "Pa" is the base unit. "Pa": 1, "hPa": 1e-2, "kPa": 1e-3, "MPa": 1e-6, "bar": 1e-5, - "atm": 1.01325e-5, + "atm": 1 / 101325, "mmHg": 1 / 133.322, "inHg": 1 / 3386.389, # Units of time. Seconds "s" is the base unit. @@ -41,14 +41,14 @@ "h": 1 / 3600, "d": 1 / 86400, # Units of mass. Kilogram "kg" is the base unit. - "mg": 1e-6, - "g": 1e-3, + "mg": 1e6, + "g": 1e3, "kg": 1, "lb": 2.20462, # Units of angle. Radian "rad" is the base unit. "rad": 1, - "deg": 1 / 180 * np.pi, - "grad": 1 / 200 * np.pi, + "deg": 180 / np.pi, + "grad": 200 / np.pi, } diff --git a/tests/unit/test_units.py b/tests/unit/test_units.py index 8c3db1d00..f63c808c3 100644 --- a/tests/unit/test_units.py +++ b/tests/unit/test_units.py @@ -68,6 +68,56 @@ def test_conversion_factor_invalid_conversion(self): class TestConvertUnits: """Tests for the convert_units function.""" + @pytest.mark.parametrize( + "unit, base_unit, value_in_base", + [ + ("mm", "m", 1e-3), + ("cm", "m", 1e-2), + ("dm", "m", 1e-1), + ("dam", "m", 1e1), + ("hm", "m", 1e2), + ("km", "m", 1e3), + ("ft", "m", 0.3048), + ("in", "m", 0.0254), + ("mi", "m", 1609.344), + ("nmi", "m", 1852), + ("yd", "m", 0.9144), + ("km/h", "m/s", 1 / 3.6), + ("knot", "m/s", 1852 / 3600), + ("mph", "m/s", 1609.344 / 3600), + ("ft/s", "m/s", 0.3048), + ("gs", "m/s^2", 9.80665), + ("ft/s^2", "m/s^2", 0.3048), + ("hPa", "Pa", 1e2), + ("kPa", "Pa", 1e3), + ("MPa", "Pa", 1e6), + ("bar", "Pa", 1e5), + ("atm", "Pa", 101325), + ("mmHg", "Pa", 133.322387415), + ("inHg", "Pa", 3386.389), + ("min", "s", 60), + ("h", "s", 3600), + ("d", "s", 86400), + ("mg", "kg", 1e-6), + ("g", "kg", 1e-3), + ("lb", "kg", 0.45359237), + ("deg", "rad", np.pi / 180), + ("grad", "rad", np.pi / 200), + ], + ) + def test_convert_units_matches_unit_definitions( + self, unit, base_unit, value_in_base + ): + """One of each unit should convert to its defined value in the base + unit, and back. The references are the exact SI definitions, so the + tolerance only allows for the rounded pound and mercury constants.""" + assert convert_units(1, unit, base_unit) == pytest.approx( + value_in_base, rel=1e-5 + ) + assert convert_units(value_in_base, base_unit, unit) == pytest.approx( + 1, rel=1e-5 + ) + def test_convert_units_same_unit(self): assert convert_units(300, "K", "K") == 300 assert convert_units(27, "degC", "degC") == 27 From e3dba001bec593ae138cc1f3231a60bf4485d281 Mon Sep 17 00:00:00 2001 From: David Rundus <114828622+rundvd@users.noreply.github.com> Date: Sat, 26 Sep 2026 01:01:58 +0000 Subject: [PATCH 02/11] TST: check FlightDataImporter converts ft/s^2 and degree columns FlightDataImporter divides imported columns by UNITS_CONVERSION_DICT entries, so the wrong ft/s^2 and deg factors made a log recorded in ft/s^2 read 10.8x too large and one recorded in degrees 3283x too large. --- .../simulation/test_flight_data_importer.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/tests/integration/simulation/test_flight_data_importer.py b/tests/integration/simulation/test_flight_data_importer.py index 9cff30d57..653222ed1 100644 --- a/tests/integration/simulation/test_flight_data_importer.py +++ b/tests/integration/simulation/test_flight_data_importer.py @@ -55,3 +55,22 @@ def test_flight_importer_ndrt(): "Can't find 'altitude' column in fd._columns" ) assert np.isclose(fd.altitude(0), 0) + + +def test_flight_importer_converts_imperial_and_degree_columns(tmp_path): + """Columns logged in ft/s^2 and degrees should be converted to SI.""" + path = tmp_path / "log.csv" + path.write_text("time,accel_ft_s2,pitch_deg\n0,32.174,90\n1,32.174,90\n") + + fd = FlightDataImporter( + paths=str(path), + columns_map={ + "time": "time", + "accel_ft_s2": "az", + "pitch_deg": "attitude_angle", + }, + units={"accel_ft_s2": "ft/s^2", "pitch_deg": "deg"}, + ) + + assert np.isclose(fd.az(0), 32.174 * 0.3048) + assert np.isclose(fd.attitude_angle(0), np.pi / 2) From 6f04be007ea6824a38b31217d246674e27226307 Mon Sep 17 00:00:00 2001 From: Gui-FernandesBR Date: Sun, 15 Nov 2026 23:28:54 -0300 Subject: [PATCH 03/11] MNT: use exact pound and mercury constants in the units table Document how the conversion table is read (units per base unit), the convention the inverted entries broke, and replace the rounded lb, mmHg and inHg constants with their exact definitions so the definition test can run at rel=1e-9. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ --- rocketpy/units.py | 11 +++++++---- tests/unit/test_units.py | 9 ++++----- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/rocketpy/units.py b/rocketpy/units.py index f044c2782..f6bde6e1c 100644 --- a/rocketpy/units.py +++ b/rocketpy/units.py @@ -2,6 +2,8 @@ from .mathutils.function import Function +# Each value is how many of that unit make one base unit (e.g. "km": 1e-3). +# Multiply by it to leave the base unit, divide by it to reach the base unit. UNITS_CONVERSION_DICT = { # Units of length. Meter "m" is the base unit. "mm": 1e3, @@ -33,8 +35,8 @@ "MPa": 1e-6, "bar": 1e-5, "atm": 1 / 101325, - "mmHg": 1 / 133.322, - "inHg": 1 / 3386.389, + "mmHg": 1 / 133.322387415, + "inHg": 1 / (25.4 * 133.322387415), # Units of time. Seconds "s" is the base unit. "s": 1, "min": 1 / 60, @@ -44,7 +46,7 @@ "mg": 1e6, "g": 1e3, "kg": 1, - "lb": 2.20462, + "lb": 1 / 0.45359237, # Units of angle. Radian "rad" is the base unit. "rad": 1, "deg": 180 / np.pi, @@ -53,7 +55,8 @@ def conversion_factor(from_unit, to_unit): - """Returns the conversion factor from one unit to another.""" + """Returns the factor that multiplies a value in ``from_unit`` to give it + in ``to_unit``. See ``UNITS_CONVERSION_DICT`` for how the table is read.""" try: incoming_factor = UNITS_CONVERSION_DICT[to_unit] except KeyError as e: diff --git a/tests/unit/test_units.py b/tests/unit/test_units.py index f63c808c3..cb0a84922 100644 --- a/tests/unit/test_units.py +++ b/tests/unit/test_units.py @@ -94,7 +94,7 @@ class TestConvertUnits: ("bar", "Pa", 1e5), ("atm", "Pa", 101325), ("mmHg", "Pa", 133.322387415), - ("inHg", "Pa", 3386.389), + ("inHg", "Pa", 25.4 * 133.322387415), ("min", "s", 60), ("h", "s", 3600), ("d", "s", 86400), @@ -109,13 +109,12 @@ def test_convert_units_matches_unit_definitions( self, unit, base_unit, value_in_base ): """One of each unit should convert to its defined value in the base - unit, and back. The references are the exact SI definitions, so the - tolerance only allows for the rounded pound and mercury constants.""" + unit, and back. The references are the exact SI definitions.""" assert convert_units(1, unit, base_unit) == pytest.approx( - value_in_base, rel=1e-5 + value_in_base, rel=1e-9 ) assert convert_units(value_in_base, base_unit, unit) == pytest.approx( - 1, rel=1e-5 + 1, rel=1e-9 ) def test_convert_units_same_unit(self): From 7c3a28eaf55c1f51748b65e39809f85b8db8305e Mon Sep 17 00:00:00 2001 From: Gui-FernandesBR Date: Sun, 15 Nov 2026 23:28:54 -0300 Subject: [PATCH 04/11] BUG: use "gs" as the metric acceleration unit of EnvironmentAnalysis "g" is gram in the units table, so converting with the metric unit_system["acceleration"] would apply a mass factor. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ --- rocketpy/environment/environment_analysis.py | 2 +- .../environment/test_environment_analysis.py | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/rocketpy/environment/environment_analysis.py b/rocketpy/environment/environment_analysis.py index 7aeae1562..07fd2d287 100644 --- a/rocketpy/environment/environment_analysis.py +++ b/rocketpy/environment/environment_analysis.py @@ -487,7 +487,7 @@ def __init_unit_system(self): self.unit_system = { "length": "m", "velocity": "m/s", - "acceleration": "g", + "acceleration": "gs", "mass": "kg", "time": "s", "pressure": "hPa", diff --git a/tests/unit/environment/test_environment_analysis.py b/tests/unit/environment/test_environment_analysis.py index cc5c22af6..1c4f9be0c 100644 --- a/tests/unit/environment/test_environment_analysis.py +++ b/tests/unit/environment/test_environment_analysis.py @@ -7,6 +7,7 @@ from rocketpy import EnvironmentAnalysis from rocketpy.tools import import_optional_dependency +from rocketpy.units import convert_units plt.rcParams.update({"figure.max_open_warning": 0}) @@ -48,6 +49,39 @@ def test_missing_timezonefinder_defaults_to_utc( assert analysis.end_date.tzinfo is not None +@pytest.mark.parametrize( + "unit_system, standard_gravity", + [("metric", 1), ("imperial", 9.80665 / 0.3048), ("SI", 9.80665)], +) +@patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPlots") +@patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPrints") +@patch.object( + EnvironmentAnalysis, + "_EnvironmentAnalysis__check_requirements", +) +def test_unit_system_acceleration_is_an_acceleration_unit( + _mock_check_requirements, + _mock_prints, + _mock_plots, + unit_system, + standard_gravity, +): + """The acceleration unit of each unit system should convert standard + gravity as an acceleration, not as a mass ("g" is gram in the table).""" + analysis = EnvironmentAnalysis( + start_date=datetime(2026, 1, 1), + end_date=datetime(2026, 1, 2), + latitude=0, + longitude=0, + timezone="UTC", + unit_system=unit_system, + ) + + converted = convert_units(9.80665, "m/s^2", analysis.unit_system["acceleration"]) + + assert converted == pytest.approx(standard_gravity, rel=1e-9) + + @pytest.mark.slow @patch("matplotlib.pyplot.show") def test_distribution_plots(mock_show, env_analysis): # pylint: disable=unused-argument From 72f96c548fe333051dd2eaecceaaf6f0ddcffce8 Mon Sep 17 00:00:00 2001 From: Gui-FernandesBR Date: Sun, 15 Nov 2026 23:29:49 -0300 Subject: [PATCH 05/11] BUG: leave the Function passed to convert_units unchanged convert_units_Functions scaled get_source() and renamed the axis labels in place, so converting a Function twice applied the factor to data already converted. Work on copies, and run every unit definition through the Function path on both axes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ --- rocketpy/units.py | 15 +++--- tests/unit/test_units.py | 99 +++++++++++++++++++++++++--------------- 2 files changed, 70 insertions(+), 44 deletions(-) diff --git a/rocketpy/units.py b/rocketpy/units.py index f6bde6e1c..6a70a91f2 100644 --- a/rocketpy/units.py +++ b/rocketpy/units.py @@ -71,8 +71,11 @@ def conversion_factor(from_unit, to_unit): def convert_units_Functions(variable, from_unit, to_unit, axis=1): """See units.convert_units() for documentation.""" + # Work on copies so the Function passed in is left unchanged + variable_source = np.array(variable.get_source(), dtype=float) + inputs = list(variable.__inputs__) + outputs = list(variable.__outputs__) # Perform conversion, take special care with temperatures - variable_source = variable.get_source() if from_unit in ["K", "degC", "degF"]: variable_source[:, axis] = convert_temperature( variable_source[:, axis], from_unit, to_unit @@ -82,16 +85,14 @@ def convert_units_Functions(variable, from_unit, to_unit, axis=1): # Rename axis labels match axis: case 0: - variable.__inputs__[0] = variable.__inputs__[0].replace(from_unit, to_unit) + inputs[0] = inputs[0].replace(from_unit, to_unit) case 1: - variable.__outputs__[0] = variable.__outputs__[0].replace( - from_unit, to_unit - ) + outputs[0] = outputs[0].replace(from_unit, to_unit) # Create new Function instance with converted data return Function( source=variable_source, - inputs=variable.__inputs__, - outputs=variable.__outputs__, + inputs=inputs, + outputs=outputs, interpolation=variable.__interpolation__, extrapolation=variable.__extrapolation__, ) diff --git a/tests/unit/test_units.py b/tests/unit/test_units.py index cb0a84922..4533f4407 100644 --- a/tests/unit/test_units.py +++ b/tests/unit/test_units.py @@ -5,6 +5,43 @@ from rocketpy.units import conversion_factor, convert_temperature, convert_units +# One of each unit and its exact value in the base unit, by SI definition. +UNIT_DEFINITIONS = [ + ("mm", "m", 1e-3), + ("cm", "m", 1e-2), + ("dm", "m", 1e-1), + ("dam", "m", 1e1), + ("hm", "m", 1e2), + ("km", "m", 1e3), + ("ft", "m", 0.3048), + ("in", "m", 0.0254), + ("mi", "m", 1609.344), + ("nmi", "m", 1852), + ("yd", "m", 0.9144), + ("km/h", "m/s", 1 / 3.6), + ("knot", "m/s", 1852 / 3600), + ("mph", "m/s", 1609.344 / 3600), + ("ft/s", "m/s", 0.3048), + ("gs", "m/s^2", 9.80665), + ("ft/s^2", "m/s^2", 0.3048), + ("hPa", "Pa", 1e2), + ("kPa", "Pa", 1e3), + ("MPa", "Pa", 1e6), + ("bar", "Pa", 1e5), + ("atm", "Pa", 101325), + ("mmHg", "Pa", 133.322387415), + ("inHg", "Pa", 25.4 * 133.322387415), + ("min", "s", 60), + ("h", "s", 3600), + ("d", "s", 86400), + ("mg", "kg", 1e-6), + ("g", "kg", 1e-3), + ("lb", "kg", 0.45359237), + ("deg", "rad", np.pi / 180), + ("grad", "rad", np.pi / 200), +] + + class TestConvertTemperature: """Tests for the convert_temperature function.""" @@ -68,43 +105,7 @@ def test_conversion_factor_invalid_conversion(self): class TestConvertUnits: """Tests for the convert_units function.""" - @pytest.mark.parametrize( - "unit, base_unit, value_in_base", - [ - ("mm", "m", 1e-3), - ("cm", "m", 1e-2), - ("dm", "m", 1e-1), - ("dam", "m", 1e1), - ("hm", "m", 1e2), - ("km", "m", 1e3), - ("ft", "m", 0.3048), - ("in", "m", 0.0254), - ("mi", "m", 1609.344), - ("nmi", "m", 1852), - ("yd", "m", 0.9144), - ("km/h", "m/s", 1 / 3.6), - ("knot", "m/s", 1852 / 3600), - ("mph", "m/s", 1609.344 / 3600), - ("ft/s", "m/s", 0.3048), - ("gs", "m/s^2", 9.80665), - ("ft/s^2", "m/s^2", 0.3048), - ("hPa", "Pa", 1e2), - ("kPa", "Pa", 1e3), - ("MPa", "Pa", 1e6), - ("bar", "Pa", 1e5), - ("atm", "Pa", 101325), - ("mmHg", "Pa", 133.322387415), - ("inHg", "Pa", 25.4 * 133.322387415), - ("min", "s", 60), - ("h", "s", 3600), - ("d", "s", 86400), - ("mg", "kg", 1e-6), - ("g", "kg", 1e-3), - ("lb", "kg", 0.45359237), - ("deg", "rad", np.pi / 180), - ("grad", "rad", np.pi / 200), - ], - ) + @pytest.mark.parametrize("unit, base_unit, value_in_base", UNIT_DEFINITIONS) def test_convert_units_matches_unit_definitions( self, unit, base_unit, value_in_base ): @@ -171,3 +172,27 @@ def test_convert_units_function_temperature_output(self): assert converted.__outputs__ == ["Temperature (degC)"] assert converted.__interpolation__ == "linear" assert converted.__extrapolation__ == "constant" + + @pytest.mark.parametrize("unit, base_unit, value_in_base", UNIT_DEFINITIONS) + def test_convert_units_function_matches_unit_definitions( + self, unit, base_unit, value_in_base + ): + """A Function should be converted with the same factors as a scalar, + on either axis, without changing the Function passed in.""" + source = np.array([[1.0, 1.0], [2.0, 2.0]]) + function = Function(source.copy(), inputs=f"x ({unit})", outputs=f"y ({unit})") + + converted_x = convert_units(function, unit, base_unit, axis=0) + converted_y = convert_units(function, unit, base_unit, axis=1) + + np.testing.assert_allclose( + converted_x.get_source()[:, 0], source[:, 0] * value_in_base, rtol=1e-9 + ) + np.testing.assert_allclose( + converted_y.get_source()[:, 1], source[:, 1] * value_in_base, rtol=1e-9 + ) + assert converted_x.__inputs__ == [f"x ({base_unit})"] + assert converted_y.__outputs__ == [f"y ({base_unit})"] + np.testing.assert_array_equal(function.get_source(), source) + assert function.__inputs__ == [f"x ({unit})"] + assert function.__outputs__ == [f"y ({unit})"] From f4ea836b28a97e0740b22eb6bb0402e5f79c1a38 Mon Sep 17 00:00:00 2001 From: Gui-FernandesBR Date: Sun, 15 Nov 2026 23:31:12 -0300 Subject: [PATCH 06/11] BUG: convert FlightDataImporter columns without editing the read data The importer divided a view of _data in place by UNITS_CONVERSION_DICT, so the stored data turned into SI while still labelled with the original units, and a unit outside the table (degC included) raised a bare KeyError. Convert through a new units.convert_to_base_unit, which handles temperatures and raises the module's ValueError. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ --- rocketpy/simulation/flight_data_importer.py | 4 +- rocketpy/units.py | 11 +++++ .../simulation/test_flight_data_importer.py | 41 +++++++++++++++++++ tests/unit/test_units.py | 30 +++++++++++++- 4 files changed, 83 insertions(+), 3 deletions(-) diff --git a/rocketpy/simulation/flight_data_importer.py b/rocketpy/simulation/flight_data_importer.py index cec357fd5..3c7c54428 100644 --- a/rocketpy/simulation/flight_data_importer.py +++ b/rocketpy/simulation/flight_data_importer.py @@ -9,7 +9,7 @@ import numpy as np from rocketpy.mathutils import Function -from rocketpy.units import UNITS_CONVERSION_DICT +from rocketpy.units import convert_to_base_unit logger = logging.getLogger(__name__) @@ -287,7 +287,7 @@ def __create_attributes(self, filepath, interpolation, extrapolation): # Convert units if necessary if units and col in units: - values /= UNITS_CONVERSION_DICT[units[col]] + values = convert_to_base_unit(values, units[col]) logger.debug("Attribute '%s' converted from %s to SI", name, units[col]) # Create Function object and set as attribute diff --git a/rocketpy/units.py b/rocketpy/units.py index 6a70a91f2..dab7dd11a 100644 --- a/rocketpy/units.py +++ b/rocketpy/units.py @@ -69,6 +69,17 @@ def conversion_factor(from_unit, to_unit): return incoming_factor / outgoing_factor +def convert_to_base_unit(variable, from_unit): + """Returns ``variable`` converted from ``from_unit`` to its base unit, or to + "K" for temperatures. ``variable`` itself is not modified.""" + if from_unit in ["K", "degC", "degF"]: + return convert_temperature(variable, from_unit, "K") + try: + return variable / UNITS_CONVERSION_DICT[from_unit] + except KeyError as e: + raise ValueError(f"Unit '{from_unit}' is not supported.") from e + + def convert_units_Functions(variable, from_unit, to_unit, axis=1): """See units.convert_units() for documentation.""" # Work on copies so the Function passed in is left unchanged diff --git a/tests/integration/simulation/test_flight_data_importer.py b/tests/integration/simulation/test_flight_data_importer.py index 653222ed1..7f864ae73 100644 --- a/tests/integration/simulation/test_flight_data_importer.py +++ b/tests/integration/simulation/test_flight_data_importer.py @@ -1,6 +1,7 @@ """Tests the FlightDataImporter class from rocketpy.simulation module.""" import numpy as np +import pytest from rocketpy.simulation import FlightDataImporter @@ -74,3 +75,43 @@ def test_flight_importer_converts_imperial_and_degree_columns(tmp_path): assert np.isclose(fd.az(0), 32.174 * 0.3048) assert np.isclose(fd.attitude_angle(0), np.pi / 2) + + +@pytest.mark.parametrize( + "unit, value_in_si", + [ + ("g", 1e-3), + ("mg", 1e-6), + ("atm", 101325), + ("grad", np.pi / 200), + ("degC", 274.15), + ], +) +def test_flight_importer_converts_column_to_si(tmp_path, unit, value_in_si): + """A column given in a non-SI unit should be converted to SI, while the + data read from the file keeps its original values.""" + path = tmp_path / "log.csv" + path.write_text("time,value\n0,1\n1,1\n") + + fd = FlightDataImporter( + paths=str(path), + columns_map={"time": "time", "value": "value"}, + units={"value": unit}, + ) + + assert np.isclose(fd.value(0), value_in_si) + data = next(iter(fd._data.values())) + np.testing.assert_array_equal(data[:, 1], [1, 1]) + + +def test_flight_importer_unsupported_unit(tmp_path): + """An unknown unit should raise the same error as the units module.""" + path = tmp_path / "log.csv" + path.write_text("time,value\n0,1\n1,1\n") + + with pytest.raises(ValueError, match="Unit 'furlong' is not supported."): + FlightDataImporter( + paths=str(path), + columns_map={"time": "time", "value": "value"}, + units={"value": "furlong"}, + ) diff --git a/tests/unit/test_units.py b/tests/unit/test_units.py index 4533f4407..ca36046c8 100644 --- a/tests/unit/test_units.py +++ b/tests/unit/test_units.py @@ -2,7 +2,12 @@ import pytest from rocketpy import Function -from rocketpy.units import conversion_factor, convert_temperature, convert_units +from rocketpy.units import ( + conversion_factor, + convert_temperature, + convert_to_base_unit, + convert_units, +) # One of each unit and its exact value in the base unit, by SI definition. @@ -196,3 +201,26 @@ def test_convert_units_function_matches_unit_definitions( np.testing.assert_array_equal(function.get_source(), source) assert function.__inputs__ == [f"x ({unit})"] assert function.__outputs__ == [f"y ({unit})"] + + +class TestConvertToBaseUnit: + """Tests for the convert_to_base_unit function.""" + + @pytest.mark.parametrize("unit, base_unit, value_in_base", UNIT_DEFINITIONS) + def test_convert_to_base_unit_matches_unit_definitions( + self, unit, base_unit, value_in_base + ): # pylint: disable=unused-argument + assert convert_to_base_unit(1, unit) == pytest.approx(value_in_base, rel=1e-9) + + def test_convert_to_base_unit_temperature_to_kelvin(self): + assert convert_to_base_unit(0, "degC") == pytest.approx(273.15) + assert convert_to_base_unit(32, "degF") == pytest.approx(273.15) + + def test_convert_to_base_unit_leaves_array_unchanged(self): + values = np.array([1.0, 2.0]) + convert_to_base_unit(values, "km") + np.testing.assert_array_equal(values, [1.0, 2.0]) + + def test_convert_to_base_unit_unsupported_unit(self): + with pytest.raises(ValueError, match="Unit 'furlong' is not supported."): + convert_to_base_unit(1, "furlong") From 2df3c0461b784f53d6b18c754c5f948b35768cc4 Mon Sep 17 00:00:00 2001 From: David Rundus <114828622+rundvd@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:38:29 -0600 Subject: [PATCH 07/11] BUG: use one height unit throughout EnvironmentAnalysis The heights of converted_pressure_level_data stayed in metres with the imperial unit system, since the converted x axis was discarded. Convert the y axis of that result instead, and read altitude_AGL_range and the pressures at 1000, 10000 and 30000 ft in the same length unit. --- rocketpy/environment/environment_analysis.py | 21 ++-- .../environment/test_environment_analysis.py | 111 +++++++++++++++++- 2 files changed, 121 insertions(+), 11 deletions(-) diff --git a/rocketpy/environment/environment_analysis.py b/rocketpy/environment/environment_analysis.py index 07fd2d287..7a577349f 100644 --- a/rocketpy/environment/environment_analysis.py +++ b/rocketpy/environment/environment_analysis.py @@ -153,7 +153,8 @@ def __init__( # pylint: disable=too-many-statements Arguments for setting the forecast on the Environment class. With this argument it is possible to change the forecast model being used. max_expected_altitude : float, optional - Maximum expected altitude for your analysis. This is used to calculate + Maximum expected altitude for your analysis, above ground level and + in the length unit of ``unit_system``. This is used to calculate plot limits from pressure level data profiles. If None is set, the maximum altitude will be calculated from the pressure level data. Default is None. @@ -208,7 +209,7 @@ def __init__( # pylint: disable=too-many-statements date=hour_date_time, latitude=self.latitude, longitude=self.longitude, - elevation=self.converted_elevation, + elevation=self.original_elevation, ) forecast_args = forecast_args or {"type": "Forecast", "file": "GFS"} env.set_atmospheric_model(**forecast_args) @@ -982,7 +983,7 @@ def converted_pressure_level_data(self): self.updated_units["height_ASL"] = self.unit_system["length"] # Convert y axis variable = convert_units( - variable=value, + variable=variable, from_unit=self.current_units[key], to_unit=conversion_dict[key], axis=1, @@ -2102,7 +2103,7 @@ def altitude_AGL_range(self): # pylint: disable=invalid-name """The altitude range for the pressure level data. The minimum altitude is always 0, and the maximum altitude is the maximum altitude of the pressure level data, or the maximum expected altitude if it is set. - Units are kept as they are in the original data. + Altitudes are in the length unit of the preferred unit system. Returns ------- @@ -2114,7 +2115,7 @@ def altitude_AGL_range(self): # pylint: disable=invalid-name if self.max_expected_altitude is None: max_altitudes = [ np.max(day_dict[hour]["wind_speed"].source[-1, 0]) - for day_dict in self.original_pressure_level_data.values() + for day_dict in self.converted_pressure_level_data.values() for hour in day_dict.keys() ] max_altitude = np.min(max_altitudes) @@ -2126,8 +2127,8 @@ def altitude_AGL_range(self): # pylint: disable=invalid-name def altitude_list(self, points=200): # pylint: disable=property-with-parameters """A list of altitudes, from 0 to the maximum altitude of the pressure level data, or the maximum expected altitude if it is set. The list is - cached so that the computation is only done once. Units are kept as they - are in the original data. + cached so that the computation is only done once. Altitudes are in the + length unit of the preferred unit system. Parameters ---------- @@ -2152,7 +2153,7 @@ def pressure_at_1000ft_list(self): """ return [ day_dict[hour]["pressure"]( - convert_units(1000, "ft", self.current_units["height_ASL"]) + convert_units(1000, "ft", self.unit_system["length"]) ) for day_dict in self.converted_pressure_level_data.values() for hour in day_dict.keys() @@ -2174,7 +2175,7 @@ def pressure_at_10000ft_list(self): # Pressure at 10000 feet return [ day_dict[hour]["pressure"]( - convert_units(10000, "ft", self.current_units["height_ASL"]) + convert_units(10000, "ft", self.unit_system["length"]) ) for day_dict in self.converted_pressure_level_data.values() for hour in day_dict.keys() @@ -2196,7 +2197,7 @@ def pressure_at_30000ft_list(self): # Pressure at 30000 feet return [ day_dict[hour]["pressure"]( - convert_units(30000, "ft", self.current_units["height_ASL"]) + convert_units(30000, "ft", self.unit_system["length"]) ) for day_dict in self.converted_pressure_level_data.values() for hour in day_dict.keys() diff --git a/tests/unit/environment/test_environment_analysis.py b/tests/unit/environment/test_environment_analysis.py index 1c4f9be0c..5f324c47f 100644 --- a/tests/unit/environment/test_environment_analysis.py +++ b/tests/unit/environment/test_environment_analysis.py @@ -3,9 +3,10 @@ from unittest.mock import patch import matplotlib as plt +import numpy as np import pytest -from rocketpy import EnvironmentAnalysis +from rocketpy import EnvironmentAnalysis, Function from rocketpy.tools import import_optional_dependency from rocketpy.units import convert_units @@ -82,6 +83,114 @@ def test_unit_system_acceleration_is_an_acceleration_unit( assert converted == pytest.approx(standard_gravity, rel=1e-9) +def _analysis_with_synthetic_data(unit_system): + """EnvironmentAnalysis whose weather files were already parsed, with one + sounding from 0 to 12 km above a launch site at 100 m.""" + heights = np.linspace(0, 12000, 25) + profiles = { + "pressure": 1000 * np.exp(-heights / 8000), + "temperature": 290 - 0.0065 * heights, + "wind_speed": 5 + heights / 1000, + "wind_velocity_x": 5 + heights / 1000, + "wind_velocity_y": 0 * heights, + } + sounding = { + key: Function( + np.column_stack((heights, values)), + inputs="Height Above Ground Level (m)", + outputs=key, + extrapolation="constant", + ) + for key, values in profiles.items() + } + with ( + patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPlots"), + patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPrints"), + patch.object(EnvironmentAnalysis, "_EnvironmentAnalysis__check_requirements"), + ): + analysis = EnvironmentAnalysis( + start_date=datetime(2026, 1, 1), + end_date=datetime(2026, 1, 2), + latitude=0, + longitude=0, + timezone="UTC", + unit_system=unit_system, + ) + vars(analysis)["_EnvironmentAnalysis__parse_pressure_level_data"] = ( + {"2026 01 01": {"12": sounding}}, + ) + vars(analysis)["_EnvironmentAnalysis__parse_surface_data"] = (*[None] * 5, 100) + return analysis + + +@patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPlots") +@patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPrints") +@patch("rocketpy.environment.environment_analysis.Environment") +@patch.object(EnvironmentAnalysis, "_EnvironmentAnalysis__check_requirements") +@patch.object(EnvironmentAnalysis, "original_elevation", 100) +@patch.object( + EnvironmentAnalysis, "original_pressure_level_data", {"2026 01 01": {"12": {}}} +) +def test_forecast_elevation_is_in_metres( + _mock_check_requirements, mock_environment, _mock_prints, _mock_plots +): + """Environment takes the elevation in metres for every unit system.""" + EnvironmentAnalysis( + start_date=datetime(2026, 1, 1), + end_date=datetime(2026, 1, 2), + latitude=0, + longitude=0, + timezone="UTC", + unit_system="imperial", + forecast_date=datetime(2026, 1, 1), + ) + + assert mock_environment.call_args.kwargs["elevation"] == 100 + + +def test_imperial_pressure_level_heights_are_in_feet(): + """Converted heights, the altitude range and the pressures at fixed heights + should all use feet, and the original data should stay in metres.""" + analysis = _analysis_with_synthetic_data("imperial") + original = analysis.original_pressure_level_data["2026 01 01"]["12"]["pressure"] + + converted = analysis.converted_pressure_level_data["2026 01 01"]["12"]["pressure"] + + assert converted.source[-1, 0] == pytest.approx(12000 / 0.3048, rel=1e-9) + assert converted.__inputs__ == ["Height Above Ground Level (ft)"] + assert original.source[-1, 0] == 12000 + assert analysis.altitude_AGL_range == pytest.approx((0, 12000 / 0.3048), rel=1e-9) + for height, values in ( + (1000, analysis.pressure_at_1000ft_list), + (10000, analysis.pressure_at_10000ft_list), + (30000, analysis.pressure_at_30000ft_list), + ): + expected = convert_units(original(height * 0.3048), "hPa", "inHg") + assert values == pytest.approx([expected], rel=1e-9) + + +@pytest.mark.parametrize("unit_system", ["metric", "imperial"]) +@pytest.mark.parametrize("read_data_first", [False, True]) +def test_environment_object_does_not_depend_on_unit_system( + unit_system, read_data_first +): + """The Environment should be the same for every unit system, whether or not + the converted data was read before creating it.""" + reference = _analysis_with_synthetic_data("SI").create_environment_object() + analysis = _analysis_with_synthetic_data(unit_system) + if read_data_first: + _ = analysis.converted_pressure_level_data + + env = analysis.create_environment_object() + + assert env.elevation == pytest.approx(reference.elevation, rel=1e-9) + for height in (100, 1000, 5000, 11000): + for name in ("pressure", "temperature", "wind_velocity_x"): + assert getattr(env, name)(height) == pytest.approx( + getattr(reference, name)(height), rel=1e-6 + ) + + @pytest.mark.slow @patch("matplotlib.pyplot.show") def test_distribution_plots(mock_show, env_analysis): # pylint: disable=unused-argument From 832bca92a6bc1f9f41cdb43f279bef8bf018bd83 Mon Sep 17 00:00:00 2001 From: David Rundus <114828622+rundvd@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:38:29 -0600 Subject: [PATCH 08/11] BUG: rename only the unit in the labels of converted Functions Converting "Maximum Height (m)" to ft gave "Maxiftuft Height (ft)". Also document convert_to_base_unit. --- rocketpy/units.py | 29 ++++++++++++++++++++++++----- tests/unit/test_units.py | 15 +++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/rocketpy/units.py b/rocketpy/units.py index dab7dd11a..aac67395c 100644 --- a/rocketpy/units.py +++ b/rocketpy/units.py @@ -70,8 +70,26 @@ def conversion_factor(from_unit, to_unit): def convert_to_base_unit(variable, from_unit): - """Returns ``variable`` converted from ``from_unit`` to its base unit, or to - "K" for temperatures. ``variable`` itself is not modified.""" + """Convert a variable to the base unit of its quantity, which is the SI unit. + + Parameters + ---------- + variable : int, float, numpy.array + Variable to be converted. It is not modified. + from_unit : string + Unit of incoming data. Any unit in ``UNITS_CONVERSION_DICT``, or one of + the temperature units "K", "degC" and "degF". + + Returns + ------- + variable : int, float, numpy.array + Variable converted to its base unit, or to "K" for temperatures. + + Raises + ------ + ValueError + If ``from_unit`` is not supported. + """ if from_unit in ["K", "degC", "degF"]: return convert_temperature(variable, from_unit, "K") try: @@ -93,12 +111,13 @@ def convert_units_Functions(variable, from_unit, to_unit, axis=1): ) else: variable_source[:, axis] *= conversion_factor(from_unit, to_unit) - # Rename axis labels + # Rename the unit in the axis label, which is given in parentheses + old_label, new_label = f"({from_unit})", f"({to_unit})" match axis: case 0: - inputs[0] = inputs[0].replace(from_unit, to_unit) + inputs[0] = inputs[0].replace(old_label, new_label) case 1: - outputs[0] = outputs[0].replace(from_unit, to_unit) + outputs[0] = outputs[0].replace(old_label, new_label) # Create new Function instance with converted data return Function( source=variable_source, diff --git a/tests/unit/test_units.py b/tests/unit/test_units.py index ca36046c8..04f55764b 100644 --- a/tests/unit/test_units.py +++ b/tests/unit/test_units.py @@ -202,6 +202,21 @@ def test_convert_units_function_matches_unit_definitions( assert function.__inputs__ == [f"x ({unit})"] assert function.__outputs__ == [f"y ({unit})"] + @pytest.mark.parametrize("axis", [0, 1]) + def test_convert_units_function_renames_only_the_unit(self, axis): + """Letters of the label that match the unit should be kept.""" + function = Function( + np.array([[0.0, 0.0], [1.0, 1.0]]), + inputs="Maximum Height (m)", + outputs="Maximum Height (m)", + ) + + converted = convert_units(function, "m", "ft", axis=axis) + + labels = [converted.__inputs__[0], converted.__outputs__[0]] + assert labels[axis] == "Maximum Height (ft)" + assert labels[1 - axis] == "Maximum Height (m)" + class TestConvertToBaseUnit: """Tests for the convert_to_base_unit function.""" From 9e87e5e44940afd303b6b2686cdb0595c9a9810a Mon Sep 17 00:00:00 2001 From: David Rundus <114828622+rundvd@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:38:29 -0600 Subject: [PATCH 09/11] BUG: convert the time column of FlightDataImporter and check its units A units entry for the time column was ignored. Time and acceleration columns now also reject units of other quantities, such as "g" (gram) for an acceleration. --- rocketpy/simulation/flight_data_importer.py | 84 ++++++++++++++++--- .../simulation/test_flight_data_importer.py | 82 +++++++++++++++++- 2 files changed, 155 insertions(+), 11 deletions(-) diff --git a/rocketpy/simulation/flight_data_importer.py b/rocketpy/simulation/flight_data_importer.py index 3c7c54428..2aa1b70bb 100644 --- a/rocketpy/simulation/flight_data_importer.py +++ b/rocketpy/simulation/flight_data_importer.py @@ -47,6 +47,12 @@ "z": "Position z (m)", } +# Used to reject units of another quantity that are easily given by mistake, +# such as "m" (meter) for a time or "g" (gram) for an acceleration. +TIME_UNITS = ("s", "min", "h", "d") +MASS_AND_ANGLE_UNITS = ("mg", "g", "kg", "lb", "rad", "deg", "grad") +ACCELERATION_ATTRIBUTES = ("acceleration", "ax", "ay", "az") + class FlightDataImporter: """A class used to import flight data from a .csv or .txt file and build an @@ -80,11 +86,16 @@ def __init__( dictionary keys must be the original column names and the values must be the desired column names. units : dict, optional - A dictionary mapping column names to desired units. + A dictionary mapping column names to the units of their data. Defaults to None, which will consider that all the data is in SI. The dictionary keys must be the original column names and the values must be the units of the data in the column. There is no need to specify the units for a column that is already in SI. + The supported units are the ones in + ``rocketpy.units.UNITS_CONVERSION_DICT``, plus "K", "degC" and + "degF" for temperatures, which are converted to K. The time column + is converted to seconds. Note that "g" is gram: accelerations in + multiples of standard gravity must use "gs". interpolation : str, optional The interpolation method to use for missing data. Defaults to "linear", see rocketpy.mathutils.Function for more @@ -98,6 +109,13 @@ def __init__( encoding : str, optional The encoding of the data file. Defaults to "utf-8". + Raises + ------ + ValueError + If a unit is not supported, if it is not a time unit for the time + column, or if it is a mass or angle unit for the ``acceleration``, + ``ax``, ``ay`` and ``az`` columns. + Notes ----- Try to avoid using forbidden characters in the column names, such as @@ -200,9 +218,9 @@ def __handle_dataset(self, filepath, delimiter, encoding): ] def __define_time_column(self, filepath): - """Defines the time column of the data frame. The time column must be in - seconds and must be named 'time'. Alternatively, you can specify the - time column using the 'columns_map' argument. + """Defines the time column of the data frame. The time column must be + named 'time'. Alternatively, you can specify the time column using the + 'columns_map' argument. Parameters ---------- @@ -228,12 +246,49 @@ def __define_time_column(self, filepath): return None raise ValueError( "Unable to determine the time column, please specify it. The time column " - + "must be in seconds and must be named 'time'. Alternatively, you " + + "must be named 'time'. Alternatively, you " + "can specify the time column using the 'columns_map' argument. " + "Available columns are: " + str(self._columns[filepath]) ) + @staticmethod + def __convert_to_si(values, name, unit): + """Converts the values of a column to SI. + + Parameters + ---------- + values : numpy.ndarray + The values of the column, which are not modified. + name : str + The name of the attribute the column is saved to. + unit : str + The unit of the values. + + Returns + ------- + numpy.ndarray + The values in SI. + + Raises + ------ + ValueError + If the unit is not supported or does not fit the attribute. + """ + converted = convert_to_base_unit(values, unit) + if name == "time" and unit not in TIME_UNITS: + raise ValueError( + f"Unit '{unit}' can't be used for '{name}'. " + f"The accepted units are: {', '.join(TIME_UNITS)}." + ) + if name in ACCELERATION_ATTRIBUTES and unit in MASS_AND_ANGLE_UNITS: + raise ValueError( + f"Unit '{unit}' can't be used for '{name}'. " + "Use 'gs' for multiples of standard gravity." + ) + logger.debug("Attribute '%s' converted from %s to SI", name, unit) + return converted + def __create_attributes(self, filepath, interpolation, extrapolation): """Creates the attributes to emulate a Flight object. @@ -251,7 +306,8 @@ def __create_attributes(self, filepath, interpolation, extrapolation): Raises ------ ValueError - If the time column is not found in the header of the file. + If the time column is not found in the header of the file, or if a + unit is not supported or does not fit its column. """ time_col = self._time_cols[filepath] units = self._units[filepath] @@ -267,6 +323,8 @@ def __create_attributes(self, filepath, interpolation, extrapolation): + "The available columns are:" + str(self._original_columns[filepath]) ) from e + if units and time_col in units: + times = self.__convert_to_si(times, "time", units[time_col]) created = [] for col, name in self._columns_map[filepath].items(): @@ -287,8 +345,7 @@ def __create_attributes(self, filepath, interpolation, extrapolation): # Convert units if necessary if units and col in units: - values = convert_to_base_unit(values, units[col]) - logger.debug("Attribute '%s' converted from %s to SI", name, units[col]) + values = self.__convert_to_si(values, name, units[col]) # Create Function object and set as attribute setattr( @@ -329,8 +386,9 @@ def read_data( A dictionary mapping column names to desired column names. Defaults to None, which will keep the original column names. units : dict, optional - A dictionary mapping column names to desired units. + A dictionary mapping column names to the units of their data. Defaults to None, which will consider that all the data is in SI. + See the class constructor for the supported units. interpolation : str, optional The interpolation method to use for missing data. Defaults to "linear", see rocketpy.mathutils.Function for more @@ -348,6 +406,12 @@ def read_data( ------- None + Raises + ------ + ValueError + If a unit is not supported, or does not fit its column. See the + class constructor for details. + Notes ----- This method handles multiple files within the same path and processes @@ -366,7 +430,7 @@ def read_data( self._files.extend(list_of_files) # Loop through the files and read each of them - for filepath in self._files: + for filepath in list_of_files: self._units[filepath] = units self._columns_map[filepath] = columns_map self._encodings[filepath] = encoding diff --git a/tests/integration/simulation/test_flight_data_importer.py b/tests/integration/simulation/test_flight_data_importer.py index 7f864ae73..dc389d5f2 100644 --- a/tests/integration/simulation/test_flight_data_importer.py +++ b/tests/integration/simulation/test_flight_data_importer.py @@ -99,7 +99,7 @@ def test_flight_importer_converts_column_to_si(tmp_path, unit, value_in_si): units={"value": unit}, ) - assert np.isclose(fd.value(0), value_in_si) + assert fd.value(0) == pytest.approx(value_in_si, rel=1e-9) data = next(iter(fd._data.values())) np.testing.assert_array_equal(data[:, 1], [1, 1]) @@ -115,3 +115,83 @@ def test_flight_importer_unsupported_unit(tmp_path): columns_map={"time": "time", "value": "value"}, units={"value": "furlong"}, ) + + +def test_flight_importer_converts_time_column(tmp_path): + """A time column given in minutes should be converted to seconds, both in + the time attribute and in the inputs of the created Functions.""" + path = tmp_path / "log.csv" + path.write_text("t,value\n0,1\n1,3\n") + + fd = FlightDataImporter( + paths=str(path), + columns_map={"t": "time", "value": "value"}, + units={"t": "min"}, + ) + + np.testing.assert_allclose(fd.time, [0, 60], rtol=1e-9) + assert fd.value(30) == pytest.approx(2, rel=1e-9) + + +def test_flight_importer_converts_standard_gravity(tmp_path): + """Accelerations logged in multiples of standard gravity use "gs".""" + path = tmp_path / "log.csv" + path.write_text("time,accel\n0,2\n1,2\n") + + fd = FlightDataImporter( + paths=str(path), + columns_map={"time": "time", "accel": "az"}, + units={"accel": "gs"}, + ) + + assert fd.az(0) == pytest.approx(2 * 9.80665, rel=1e-9) + + +@pytest.mark.parametrize( + "column, name, unit", + [ + ("accel", "az", "g"), + ("accel", "ax", "deg"), + ("accel", "acceleration", "rad"), + ("time", "time", "m"), + ], +) +def test_flight_importer_unit_of_another_quantity(tmp_path, column, name, unit): + """Time and acceleration columns should reject units of other quantities, + such as "g", which is gram.""" + path = tmp_path / "log.csv" + path.write_text("time,accel\n0,1\n1,1\n") + columns_map = {"time": "time", "accel": "az"} + columns_map[column] = name + + with pytest.raises(ValueError, match=f"Unit '{unit}' can't be used for '{name}'"): + FlightDataImporter( + paths=str(path), columns_map=columns_map, units={column: unit} + ) + + +def test_flight_importer_unsupported_time_unit(tmp_path): + """An unknown unit for the time column should not be ignored.""" + path = tmp_path / "log.csv" + path.write_text("time,value\n0,1\n1,1\n") + + with pytest.raises(ValueError, match="Unit 'furlong' is not supported."): + FlightDataImporter( + paths=str(path), + columns_map={"time": "time", "value": "value"}, + units={"time": "furlong"}, + ) + + +def test_flight_importer_second_read_keeps_first_file(tmp_path): + """Reading another file should not convert the first one again.""" + first, second = tmp_path / "first.csv", tmp_path / "second.csv" + first.write_text("time,first_value\n0,1\n1,3\n") + second.write_text("time,second_value\n0,1\n1,3\n") + columns_map = {name: name for name in ("time", "first_value", "second_value")} + fd = FlightDataImporter(paths=str(first), columns_map=columns_map) + + fd.read_data(str(second), columns_map=columns_map, units={"time": "min"}) + + assert fd.first_value(0.5) == pytest.approx(2, rel=1e-9) + assert fd.second_value(30) == pytest.approx(2, rel=1e-9) From 89ed02c8f4266d0af6e682bc0ac2fca127af6500 Mon Sep 17 00:00:00 2001 From: David Rundus <114828622+rundvd@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:38:29 -0600 Subject: [PATCH 10/11] DOC: add the units conversion fix to the changelog --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 812b6f3c3..b773fbf2c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,9 @@ Attention: The newest changes should be on top --> ### 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) +- BUG: Fix inverted and wrong factors in the units conversion table. Results computed with `ft/s^2`, `atm`, `mg`, `g`, `deg` and `grad` change, and those with `lb`, `mmHg` and `inHg` change by at most about 3 parts per million. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199) +- BUG: Use one height unit throughout `EnvironmentAnalysis`. With the imperial unit system, the pressures at 1000, 10000 and 30000 ft change, since they were evaluated at the wrong height. `original_pressure_level_data` now keeps the units of the file. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199) +- BUG: `FlightDataImporter` converts the time column when its unit is given, and raises `ValueError` for unsupported units (it was `KeyError`), for a time column in a unit that is not of time, and for accelerations in mass or angle units. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199) ## [v1.14.0] - 2026-11-29 From b64007276ca9abc54fd114ec1ecd0fb3c549e48f Mon Sep 17 00:00:00 2001 From: Gui-FernandesBR Date: Sat, 5 Dec 2026 22:19:24 -0300 Subject: [PATCH 11/11] BUG: correct hourly forecast wind profiles Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- rocketpy/plots/environment_analysis_plots.py | 8 ++- .../environment/test_environment_analysis.py | 57 +++++++++++++++++++ 2 files changed, 63 insertions(+), 2 deletions(-) diff --git a/rocketpy/plots/environment_analysis_plots.py b/rocketpy/plots/environment_analysis_plots.py index f043fa491..be32163c0 100644 --- a/rocketpy/plots/environment_analysis_plots.py +++ b/rocketpy/plots/environment_analysis_plots.py @@ -1535,9 +1535,13 @@ def wind_speed_profile_grid(self, clear_range_limits=False, *, filename=None): if self.env_analysis.forecast: forecast = self.env_analysis.forecast y = self.env_analysis.average_wind_speed_profile_by_hour[hour][1] - x = forecast[hour].wind_speed.get_value_opt(y) * convert_units( - 1, "m/s", self.env_analysis.unit_system["wind_speed"] + altitude_asl_m = ( + convert_units(y, self.env_analysis.unit_system["length"], "m") + + self.env_analysis.original_elevation ) + x = forecast[str(hour)].wind_speed.get_value_opt( + altitude_asl_m + ) * convert_units(1, "m/s", self.env_analysis.unit_system["wind_speed"]) ax.plot(x, y, "b--") ax.label_outer() diff --git a/tests/unit/environment/test_environment_analysis.py b/tests/unit/environment/test_environment_analysis.py index 5f324c47f..17d8aac2d 100644 --- a/tests/unit/environment/test_environment_analysis.py +++ b/tests/unit/environment/test_environment_analysis.py @@ -1,12 +1,15 @@ import os from datetime import datetime +from types import SimpleNamespace from unittest.mock import patch import matplotlib as plt +from matplotlib import pyplot import numpy as np import pytest from rocketpy import EnvironmentAnalysis, Function +from rocketpy.plots.environment_analysis_plots import _EnvironmentAnalysisPlots from rocketpy.tools import import_optional_dependency from rocketpy.units import convert_units @@ -123,6 +126,60 @@ def _analysis_with_synthetic_data(unit_system): return analysis +def _forecast_plot_with_imperial_heights(): + """Create an hourly forecast plot input with keys and heights in their + respective source units.""" + heights_agl_ft = np.array([0.0, 1000.0, 2000.0]) + profile = np.array([1.0, 2.0, 3.0]) + hours = (0, 6, 12, 18) + wind_speed = Function( + np.array([[0.0, 0.0], [5000.0, 5.0]]), + inputs="Height Above Sea Level (m)", + outputs="Wind Speed (m/s)", + ) + forecast = {str(hour): SimpleNamespace(wind_speed=wind_speed) for hour in hours} + analysis = SimpleNamespace( + hours=list(hours), + average_wind_speed_profile_by_hour={ + hour: [profile, heights_agl_ft] for hour in hours + }, + forecast=forecast, + unit_system={"length": "ft", "wind_speed": "m/s"}, + original_elevation=100, + ) + plots = object.__new__(_EnvironmentAnalysisPlots) + plots.env_analysis = analysis + return plots, wind_speed, heights_agl_ft + + +def test_wind_speed_profile_grid_handles_string_forecast_keys(): + """Forecasts keyed by string hours should plot against integer analysis hours.""" + plots, _, _ = _forecast_plot_with_imperial_heights() + + try: + with patch("rocketpy.plots.environment_analysis_plots.show_or_save_plot"): + plots.wind_speed_profile_grid() + assert len(pyplot.gcf().axes) == 4 + finally: + pyplot.close("all") + + +def test_wind_speed_profile_grid_converts_agl_heights_to_asl_metres(): + """Forecast profiles use ASL metres, unlike the plotted imperial AGL heights.""" + plots, wind_speed, heights_agl_ft = _forecast_plot_with_imperial_heights() + expected_asl_m = convert_units(heights_agl_ft, "ft", "m") + 100 + expected_wind_speed = wind_speed.get_value_opt(expected_asl_m) + + try: + with patch("rocketpy.plots.environment_analysis_plots.show_or_save_plot"): + plots.wind_speed_profile_grid() + forecast_line = pyplot.gcf().axes[0].lines[1] + finally: + pyplot.close("all") + + np.testing.assert_allclose(forecast_line.get_xdata(), expected_wind_speed) + + @patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPlots") @patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPrints") @patch("rocketpy.environment.environment_analysis.Environment")